Syntax error when map() returns LIST

后端 未结 2 853
执笔经年
执笔经年 2021-01-17 17:32

This works,

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

but this

2条回答
  •  花落未央
    2021-01-17 18:20

    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;
      

提交回复
热议问题