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

A coworker brought this completely puzzling perl behavior to my attention. I narrowed it down to
my %hash = map { "$_" => 1 } qw(a b c);
which throws a syntax error, up to perl 5.10. Does anyone know why the (admittedly superfluous) quotes throw perl off?

Replies are listed 'Best First'.
Re: Puzzling syntax error
by repellent (Priest) on Aug 15, 2008 at 18:31 UTC
    Part 3 of Making References has a good explanation:
    # leading +{ disambiguate expression to mean HASH reference sub hashem { { @_ } } # silently wrong sub hashem { +{ @_ } } # ok sub hashem { return { @_ } } # ok # leading {; disambiguate expression to mean BLOCK sub showem { { @_ } } # ambiguous (currently ok, but may change +) sub showem { {; @_ } } # ok sub showem { { return @_ } } # ok
Re: Puzzling syntax error
by dreadpiratepeter (Priest) on Aug 15, 2008 at 17:52 UTC
    The issue is that the => expression in the {} cause the interpreter to read the whole expression as a hash-ref rather than a code block, either of the suggested fixes will make the compiler do the right thing.


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."
Re: Puzzling syntax error
by MidLifeXis (Monsignor) on Aug 15, 2008 at 17:40 UTC

    Changing the code to:

    my %hash = map { ("$_" => 1) } qw(a b c);

    also takes care of the error, although it does not answer your original question :)

    --MidLifeXis

      As does the semi-colon trick
      my %hash = map {; "$_" => 1 } qw(a b c);

      Update:

      I thought I'd better explain this idiom since Lawliet /msg'ed me about it.

      Braces in perl are used for hashrefs and for blocks and sometimes perl has to "guess" at the intended meaning. Sometimes (as in this case), perl gets it wrong. The addition of a semicolon convinces perl it's a block, not a hashref.

      At least that's how I understand it :-)


      Unless I state otherwise, all my code runs with strict and warnings