Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error when map() returns LIST

Tags:

perl

This works,

print map { $_." x" => $_ } 1..5;
print map { ("$_ x" => $_) } 1..5;
print map { ("$_ x") => $_ } 1..5;

but this throws syntax error,

print map { "$_ x" => $_ } 1..5;

Is this documented bug, undocumented bug, or I can't see why this should not compile?

Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST

like image 246
mpapec Avatar asked Jul 01 '15 15:07

mpapec


1 Answers

From perlref

Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.

To make your intentions clearer and to help the parser,

  • Say +{...} to unambiguously specify a hash reference

    @list_of_hashrefs = map +{ "$_ x" => $_ }, 1..5;
    
  • Say {; ...} to unambiguously specify a code block

    %mappings = map {; "$_ x" => $_ } 1..5;
    
like image 100
mob Avatar answered Oct 21 '22 15:10

mob