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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |