The reason your map gives you the empty string in spite of your if is that it always gives you the last expression evaluated, much like do or a sub. Consider this timeless classic (from Evil Interview Questions):

sub baz { return 11 unless shift } print 'baz(5): ', baz(5), "\n"; print 'baz(0): ', baz(0), "\n"; __END__ baz(5): 5 baz(0): 11

If you want to take something out of a list processed with map, have the block explicitly return an empty list.

my @a = ( qw (onexxx txwxo txhrexe xfourx xxx five) ); my @b = map { $_ =~ s/x//g; $_ ? $_ : (); } @a; print Dumper(\@b); __END__ $VAR1 = [ 'one', 'two', 'three', 'four', 'five' ];

As a side note, you should know that modification of $_ inside map modifies the original list element. Your code (and mine) leaves @a looking like this:

$VAR1 = [ 'one', 'two', 'three', 'four', '', 'five' ];

You can use Benchmark to try to find the most efficient way to do something, but for something like this I think you'd have to have a pretty long list before it would make a significant difference. It's generally best to use the most easily understood code until profiling tells you that something is worth optimizing.


In reply to Re: Basic list manipulation, and a bit of map() confusion... by kyle
in thread Basic list manipulation, and a bit of map() confusion... by cmv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.