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

I have two lines of similar code, the first works fine while the second produces a syntax error. What is happening?
%hash = map { $_, "$var/$_" } @array; # Works great %hash = map { "$var/$_", $_ } @array; # Syntax Error!
This one works as expected with only slight modification:
%hash = map { "$var/".$_, $_ } @array; # Also works.
Thanks

Replies are listed 'Best First'.
Re: Using map to assign to a hash
by jeffa (Bishop) on Jun 08, 2004 at 15:30 UTC

    The answer is in the docs for map: perldoc -f map.

     "{" starts both hash references and blocks, so "map { ..." could 
     be either the start of map BLOCK LIST or map EXPR, LIST. Because
     perl doesn’t look ahead for the closing "}" it has to take a guess
     at which its dealing with based what it finds just after the "{".
     Usually it gets it right, but if it doesn’t it won’t realize
     something is wrong until it gets to the "}" and encounters the
     missing (or unexpected) comma. The syntax error will be reported
     close to the "}" but you’ll need to change something near the "{"
     such as using a unary "+" to give perl some help ...
    
    The docs then list some examples, i prefer the syntax BrowserUk replied with, myself. You can also use parens, FWIW:
    %hash = map (("$var/$_", $_), @array);

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Using map to assign to a hash
by BrowserUk (Patriarch) on Jun 08, 2004 at 15:30 UTC

    Looks like a bug to me, but if you put parens around the list it makes it 'go away';

    %hash = map { ( "$var/$_", $_ ) } @array;

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: Using map to assign to a hash
by Grygonos (Chaplain) on Jun 08, 2004 at 17:00 UTC

    Also worth noting, putting parens only around the key definition fixes it as well. ie

    map{("$var/$_"),$_}@array
    So simply adding extra clarity to the key definition is the main fix (as stated by jeffa in his perldoc ref).