这会在Perl v5.20中引发错误:
use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number $_" => 2*$_ } @a;
错误:
syntax error at a.pl line 4, near "} @a"
Execution of a.pl aborted due to compilation errors.
这不是:
use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number ".$_ => 2*$_ } @a;
为什么在
$_
BLOCK中不允许map
内插?
最佳答案
map
具有两种语法:
map BLOCK LIST
map EXPR, LIST
Perl必须确定您使用的语法。问题在于
BLOCK
和EXPR
都可以以{
开头,因为{ ... }
可以是哈希构造函数(例如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.
因此,在您的情况下,您可以使用
my %b = map {; "number $_" => 2*$_ } @a;
相关:Difference between returning +{} or {} in perl from a function, and return ref or value
关于perl - 为什么在 `map` BLOCK中没有插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47311313/