I have some questions about Perl’s ‘map’ function.
Specifically:
-
How does
%hash = map {$_ => 1} @array
create a hash mapping array’s elements to 1? How does block return a list of two elements? I thought block returns its last value. Does => implicitly create a list, as opposed to ‘,’ that returns its right argument?
-
Why does
%hash = map ($_ => 1), @array
not work? I am trying to return a list of two elements here… And how does prepending ‘+’ before ‘(‘ fix it, from the parser’s point of view?
Question 1: map blocks are run list context, and as such are allowed to return zero, one or more values.
mapreturns them all. ‘,‘ or ‘=>‘return their right side in scalar context, but both sides in list context. See perlop for the details.Question 2:
%hash = map ($_ => 1), @arrayis interpreted as%hash = (map($_, 1), @array). In other words, it returns (1, @array). In%hash = map +($_ => 1), @array, the + indicates that the () doesn’t refer to an argument list, so it is interpreted as map(+($_ => 1), @array);The lesson of the day: always use accolades around your map expression, that way you won’t be bitten by these kinds of issues.