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

program1:

{ 7; }

program2:

{ 7, 10; }

Program1 compiles just fine. (Define a block, evaluate the statement 7; in that block, exit the block.)

However, Program2 does not compile. I suspect this has something to do with Perl "thinking" I'm trying to evaluate an anonymous hashref expression as a statement (which I'm not.)

Does anyone know what the syntax error Perl finds here is about?

Thanks, Ed Update: Thanks for everyone's help. To clarify, I wasn't using this in a purposeful program, I was just trying to understand how Perl works, and it was frustrating me that I couldn't figure out why 2 very similar programs were being parsed so differently.

Replies are listed 'Best First'.
Re: failure to compile list eval in block
by LanX (Saint) on Dec 16, 2012 at 00:22 UTC
    Perl's parser uses heuristics to make the distinction between hashes and code-blocks.

    Because of the numbers (remember => is just a fat comma) this is interpreted as a hash.

    eliminating the ; helps seeing what's happening

    > perl -MO=Deparse { 7, 10 } __END__ +{7, 10}; # <-- a literal hash

    But what do you expect a codeblock with 7,10 to do?

    EDIT:

    one workaround to help the parser understand your intentions is an early semicolon

    perl -MO=Deparse { ; 7,10; } __END__ { '???', '???'; # <-- constants in a codeblock }

    Cheers Rolf

Re: failure to compile list eval in block
by Athanasius (Archbishop) on Dec 16, 2012 at 02:39 UTC
Re: failure to compile list eval in block
by ikegami (Patriarch) on Dec 16, 2012 at 13:45 UTC
    The usual disambiguators:
    {; ... } # Block +{ ... } # Hash constructor

    For example,

    >perl -ce"{ 1, 2; }" syntax error at -e line 1, near "; }" -e had compilation errors. >perl -ce"{; 1, 2; }" -e syntax OK >perl -ce"map { f() }, @a" syntax error at -e line 1, near "}," -e had compilation errors. >perl -ce"map +{ f() }, @a" -e syntax OK
Re: failure to compile list eval in block
by Anonymous Monk on Dec 16, 2012 at 01:04 UTC
    B::Deparse is B::Deparse