这是我不明白的事情。
该脚本工作正常(注意映射函数中的串联):
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %aa = map { 'a' . '' => 1 } (1..3);
print Dumper \%aa;
__END__
output:
$VAR1 = {
'a' => 1
};
但如果没有串联,地图就无法工作。这是我期望工作的脚本,但它不起作用:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %aa = map { 'a' => 1 } (1..3);
print Dumper \%aa;
__END__
output:
Not enough arguments for map at e.pl line 7, near "} ("
syntax error at e.pl line 7, near "} ("
Global symbol "%aa" requires explicit package name at e.pl line 9.
Execution of e.pl aborted due to compilation errors.
您能解释一下这种行为吗?
Perl 使用启发式方法来决定您是否使用:
map { STATEMENTS } LIST; # or
map EXPR, LIST;
因为虽然“{”通常是块的开始,但它也可能是哈希引用的开始。
这些启发式方法不会在令牌流中向前看很远(IIRC 两个令牌)。
您可以使用以下命令强制将“{”解释为块:
map {; STATEMENTS } LIST; # the semicolon acts as a disambigator
您可以使用以下命令强制将“{”解释为哈希:
map +{ LIST }, LIST; # the plus sign acts as a disambigator
grep
遭受同样的痛苦。 (技术上也是如此do
,因为 hashref 可以作为参数给出,然后该参数将被字符串化并被视为文件名。但这很奇怪。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)