为什么在`map` BLOCK中没有插值?

jlo*_*ren 9 perl perl-data-structures

这会在Perl v5.20中引发错误:

use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number $_" => 2*$_ } @a;
Run Code Online (Sandbox Code Playgroud)

错误:

syntax error at a.pl line 4, near "} @a"
Execution of a.pl aborted due to compilation errors.
Run Code Online (Sandbox Code Playgroud)

这不是:

use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number ".$_ => 2*$_ } @a;
Run Code Online (Sandbox Code Playgroud)

为什么$_mapBLOCK 中不允许插值?

ike*_*ami 14

map 有两种语法:

map BLOCK LIST
map EXPR, LIST
Run Code Online (Sandbox Code Playgroud)

Perl必须确定您使用的语法.问题是,既BLOCKEXPR可启动{,因为{ ... }可散列的构造函数(例如my $h = { a => 1, b => 2 };).

这意味着Perl的语法含糊不清.当遇到歧义时,perl在向前看一点之后猜测你的意思.在你的情况下,它猜错了.它猜测{是哈希构造函数的开始而不是块的开始.您需要明确消除歧义.

以下是消除块和散列构造函数歧义的便捷方法:

+{ ... }   # Not a valid block, so must be a hash constructor.
{; ... }   # Perl looks head, and sees that this must be a block.
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下,你可以使用

my %b = map {; "number $_" => 2*$_ } @a;
Run Code Online (Sandbox Code Playgroud)

相关:从函数返回perl中的+ {}或{}与返回ref或value之间的区别