Perl 无法使用块中的2个元素列表分析映射
以下Perl脚本将无法编译:Perl 无法使用块中的2个元素列表分析映射,perl,Perl,以下Perl脚本将无法编译: #!/usr/bin/env perl use warnings; use strict; my $vex = [ { _dirty => "muddy waters" } ]; print map { "$_", $vex->[$_]{_dirty} } ( 0 .. $#$vex ); 产出: syntax error at map.pl line 8, near "} ( " Execution of map.pl aborted due
#!/usr/bin/env perl
use warnings;
use strict;
my $vex = [ { _dirty => "muddy waters" } ];
print map { "$_", $vex->[$_]{_dirty} } ( 0 .. $#$vex );
产出:
syntax error at map.pl line 8, near "} ( "
Execution of map.pl aborted due to compilation errors.
我可以通过将2元素列表放在括号中来解决这个问题
print map { ( "$_", $vex->[$_]{_dirty} ) } ( 0 .. $#$vex );
或者,删除any变量周围的引号可以消除解析问题,但在最初更复杂的用法中需要这些引号
Perl中的Bug?我已经开始报告了。:
{
启动哈希引用和块,因此映射{…
可以是
map BLOCK LIST或map EXPR,LIST.的开头,因为Perl看起来
在结束之前}它必须猜测它正在处理的是什么
根据调查结果
{
。通常它是正确的,但如果
在到达}
和
遇到缺少(或意外)的逗号。语法错误将为
在}
附近报告,但您需要更改{
例如,使用一元+
或分号为Perl提供一些帮助:
或使用+{
强制anon哈希构造函数:
获取匿名哈希的列表,每个哈希只有一个条目
就我个人而言,我更喜欢
映射{;..
来强制它将{
解释为块的开头。将右括号向左移动;)
%hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong
%hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right
%hash = map {; "\L$_" => 1 } @array # this also works
%hash = map { ("\L$_" => 1) } @array # as does this
%hash = map { lc($_) => 1 } @array # and this.
%hash = map +( lc($_) => 1 ), @array # this is EXPR and works!
%hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
@hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
# comma at end