http://qs1969.pair.com?node_id=468605

palette has asked for the wisdom of the Perl Monks concerning the following question:

Hi all

I recently came across something like map + . I learnt the difference between map and map + is like, map returns a hash while map + return array of anonymous hash.

Can anyone of you can tell me in which context map and map + is used with examples ie; why we require a hash in one place and why an array of anonymous hash in another.

Thankyou

Replies are listed 'Best First'.
Re: map +
by gellyfish (Monsignor) on Jun 21, 2005 at 09:23 UTC

Er map + is not a separate thing to map it is simply that on occasion the plus sign (the otherwise no-op unary addition ) might be necessary to disambiguate the bare block and prevent it from being parsed as an anonymous hash.

/J\

Re: map +
by tlm (Prior) on Jun 21, 2005 at 11:07 UTC

The unary operator + is often used to disambiguate syntax that would otherwise confuse perl. In the case of map this can happen in two different situations. One is when the first non-whitespace character after the map keyword is a (. The other one is when this character is a { ...

the lowliest monk

Re: map +
by borisz (Canon) on Jun 21, 2005 at 10:09 UTC
The + is just to point the perl parser into the right direction see map.
```  %hash = map {  "\L\$_", 1  } @array  # perl guesses EXPR.  wrong
%hash = map { +"\L\$_", 1  } @array  # perl guesses BLOCK. right
%hash = map { ("\L\$_", 1) } @array  # this also works
%hash = map {  lc(\$_), 1  } @array  # as does this.
%hash = map +( lc(\$_), 1 ), @array  # this is EXPR and works!

%hash = map  ( lc(\$_), 1 ), @array  # evaluates to (1, @array)

or to force an anon hash constructor use "+{"

@hashes = map +{ lc(\$_), 1 }, @array # EXPR, so needs , at end