[Edinburgh-pm] syntax error weirdness

Jonathan Barber jon at trinity.fluff.org
Fri Aug 5 01:25:55 PDT 2005


On Fri, Aug 05, 2005 at 12:58:01AM +0100, David Baird wrote:
> dave at evesham$ perl -e 'map { $_,1 } "x"'
> dave at evesham$ perl -e 'map { "$_" } "x"'
> dave at evesham$ perl -e 'map { "$_",1 } "x"'
> syntax error at -e line 1, near "} "x""
> Execution of -e aborted due to compilation errors.
> dave at evesham$ perl -v
> 
> This is perl, v5.8.6 built for i386-freebsd-64int
> 
> Anybody know why the third line shouldn't compile? Just seems weird.

I think it's down to perl trying to guess whether the curly braces are a
block, expression or a hash ref. From the map fucntion's perldoc
(perldoc -f map):

=== begin quote ===

"{" 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:

    %hash = map {  "\L$_", 1  } @array  # perl guesses EXPR.  wrong

=== end quote ===

This is what you're running into. Perl thinks your third expression is a
hash ref, and so you get a syntax error, because map expects a BLOCK or
EXPR as it's first argument.

> d.
-- 
Jon


More information about the Edinburgh-pm mailing list