map function problem

Discussion in 'Perl Misc' started by George Kinley, Oct 5, 2004.

  1. Hi
    I have following command
    @ar1=map {if (/\\/) {$_}} @arr;
    which populates the ar1 with where it files"\" in @arr BUT it also
    appends BLANK records where it does'nt ,
    my question is how to avoid appending blank records
     
    George Kinley, Oct 5, 2004
    #1
    1. Advertisements

  2. George Kinley

    Anno Siegel Guest

    Using map? That would be

    my @ar1=map /\\/ ? $_ : (), @arr;

    but that's really a job for grep:

    my @ar1 = grep /\\/, @arr;

    Anno
     
    Anno Siegel, Oct 5, 2004
    #2
    1. Advertisements

  3. The return value of a block is the value of the last expression
    evaluated in that block.

    In then case of a block where the last statement is an unsatified if
    statement without an else clause the last expression executed is the
    condition.

    $foo = do { if ( 0 ) { 666 } }; # $foo = 0
    $foo = do { if ( 0 ) { 666 } else { 777 }; # $foo = 777
    $foo = do { if ( 1 ) { 666 } }; # $foo = 666
    $foo = do { if ( '' ) { 666 } }; # $foo = ''
    $foo = do { if ( undef ) { 666 } }; # $foo = undef

    However I would not want to assume this behaviour would never change.

    If you want to use an if statement in a non-void context always give it
    an appropriate else clause...

    @ar1=map { if (/\\/) { $_ } else { () } } @arr;

    Of course, if you are goint to put the whole if () {} else {} on one
    line it would be more conventional to use ?: instead.

    Some people dislike using if in a non-void context altogether - but I
    often find that for non-trivial expressions it is less unreadable than
    the ?: approach. (Although often factoring-out the inline if altogether
    is better still).

    my %h = (
    THIS => 1,
    THAT => 2,
    do {
    if ( wibble() ) {
    ( WIBBLE => 'lots of stuff that really would make you' .
    'loose track of where the ?: started' );
    } else {
    ();
    }
    },
    OTHER => 777,
    );
     
    Brian McCauley, Oct 6, 2004
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.