perl

Syntax Error Using Double Quoted String and Fat Comma with map


I have a syntax error in a Perl script that I don't understand:

# map BLOCK LIST
map { "/$_" => 1 } qw(foo bar baz);   # syntax error at .. line 1, near "} qw(foo bar baz)"

I have to rewrite it like this:

map { '/' . $_ => 1 } qw(foo bar baz);  # no error

This piece of code works on the other hand:

# Hash reference.
{ "/$_" => 1 };

I am using Perl 5.34.0.


Solution

  • Try putting a semicolon after opening curly brace. I'd stick with . $_ though.

    From perlfunc on 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 it's dealing with based on 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 "}"

    I'd recommend reading on it.