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

Greetings monks,

I believe a co-worker has discovered a bug in the Perl interpreter or at least he's found an interesting way to misuse it.

$ perl -Mstrict -Mwarnings -e 'map{ "$_" => 1 } ();' syntax error at -e line 1, near "} (" $ perl -Mstrict -Mwarnings -e 'map{ $_ => 1 } ();' $ perl -Mstrict -Mwarnings -e 'my $z = "z"; map{ "$z$_" => 1 } ();' syntax error at -e line 1, near "} ("

In the above lines, the first is the reduction of the problem to its most basic form albeit in a useless manner. The second one works ok. The third is the "interesting" one in that it's something you might actually want to do but it fails.

Thanks in advance for any thoughts you might have.

Replies are listed 'Best First'.
Re: Error with doublequotes in map
by eric256 (Parson) on Feb 12, 2007 at 18:28 UTC

    Map has two formates map BLOCK LIST and map EXPR, LIST the difference is that comma. For some reason the quotes at the begging of the block trick perl into thinking it is an expression instead of a block.


    ___________
    Eric Hodges

      Yup, it's thinking it's the LIST form with a hashref missing a trailing comma before the empty parens rather than BLOCK. If you parenthesize things it'll behave as well.

      $ perl -MO=Deparse,-p -Mstrict -Mwarnings -e 'map{("$_" => 1)} ();' use warnings; use strict 'refs'; map({("$_", 1);} ()); -e syntax OK

      Strange and surprising, yes. "Bug", hrmmm . . . I'd say more ambiguous corner of the grammar.

        Just for convenient reference:

        The standard ways to help Perl interpret expression (hash ref) vs. block correctly, is like this:

        map +{ "$_" => 1 }, @list # + => expression (hash ref) (+ comma) map {; "$_" => 1 } @list # ; => block (no comma)
        interestingly enough, if you leave the -p off of Deparse, it gives you
        map {"$_", 1;} ();
        which perl says is a syntax error.
      That makes a lot of sense! I'll pass it along. Thanks! Sorry for the Anonymous post. I didn't realize I wasn't logged in :|

        Also, use your perlbug program the next time you want to report a bug in perl. That goes to the people who actually deal with it.

        ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊