in reply to Unexpected behavior with "map"
G'day Clovis_Sangrail,
That's a mistake that I also seem to make from time to time. [I see ++runrig has provided an explanation.]
I usually use map with braces so when I get a list of boolean values returned from something like:
map { s/match/replace/ } @array
It's easily fixed like this:
map { s/match/replace/; $_ } @array
As you've been delving into the map documentation to understand more closely how map operates, you might also be interested to know that you can return nothing from a map expression by causing the expression to be evaluated as an empty list. For example, this code:
my @x = qw{a b a c bab aca}; my @y = map { /(.?a.?)/ ? $1 : () } @x; print "|$_|\n" for @y;
outputs:
|a| |a| |bab| |ac|
Also note how that differs from grep which you could emulate with that map expression by changing $1 to $_. This code:
my @x = qw{a b a c bab aca}; my @y = map { /(.?a.?)/ ? $_ : () } @x; print "|$_|\n" for @y;
and this code
my @x = qw{a b a c bab aca}; my @y = grep { /(.?a.?)/ } @x; print "|$_|\n" for @y;
both produce identical output:
|a| |a| |bab| |aca|
Obviously, there's really no point in writing that extra code (and, presumably, causing the extra processing) to make map emulate grep. However, it's feasible that you could have a function that operated as either based on a flag — I can't think of a situation where I've ever needed to do that but, if it did arise, it could be easily implemented like this:
$ perl -e ' my $use_grep = 0; my @x = qw{a b a c bab aca}; my @y = map { /(.?a.?)/ ? $use_grep ? $_ : $1 : () } @x; print "|$_|\n" for @y; ' |a| |a| |bab| |ac|
$ perl -e ' my $use_grep = 1; my @x = qw{a b a c bab aca}; my @y = map { /(.?a.?)/ ? $use_grep ? $_ : $1 : () } @x; print "|$_|\n" for @y; ' |a| |a| |bab| |aca|
-- Ken
|
|---|