以下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 to compilation errors.
我可以通过将 2 元素列表放在括号内来解决此问题
print map { ( "$_", $vex->[$_]{_dirty} ) } ( 0 .. $#$vex );
或者,删除 any 变量周围的引号可以消除解析问题,但在原始的、更复杂的用法中需要这些。
Perl 中的错误? 我已经提前报告了。
perldoc -f map:
{
同时启动哈希引用和块,因此map { ...
可以是 地图块列表或地图列表的开头。 因为 Perl 看起来不 在收盘}
之前,它必须猜测它正在处理什么 基于它在{
. 通常它做对了,但如果它 难道它不会意识到有什么不对劲,直到它到了}
和 遇到缺少(或意外)逗号。 语法错误将是 报告靠近}
,但您需要更改靠近{
比如使用一元+
或分号给 Perl 一些帮助:
%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)
或者强制使用
+{
anon 哈希构造函数:
@hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
# comma at end
获取匿名哈希的列表,每个哈希值只有一个条目。
就个人而言,我更喜欢map {; ...
强制它将{
解释为 BLOCK 的开始。