这是我不明白的事情.
此脚本正常工作(注意地图功能中的连接):
#!/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
};
Run Code Online (Sandbox Code Playgroud)
但是没有连接,地图就不起作用了.这是我希望工作的脚本,但它没有:
#!/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.
Run Code Online (Sandbox Code Playgroud)
你能解释一下这种行为吗?
tob*_*ink 12
Perl使用启发式方法来决定您是否正在使用:
map { STATEMENTS } LIST; # or
map EXPR, LIST;
Run Code Online (Sandbox Code Playgroud)
因为虽然"{"通常是块的开头,但它也可能是hashref的开头.
这些启发式方法在令牌流中没有向前看(IIRC两个令牌).
您可以使用以下命令强制"{"被解释为块:
map {; STATEMENTS } LIST; # the semicolon acts as a disambigator
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令强制"{"解释为哈希:
map +{ LIST }, LIST; # the plus sign acts as a disambigator
Run Code Online (Sandbox Code Playgroud)
grep同样受苦.(技术上也是如此do,因为hashref可以作为参数给出,然后将其进行字符串化处理,就像它是一个文件名一样.但这只是奇怪的.)
每对Documentation为map:
因为Perl没有预见到结束,
}所以它必须根据它在之后发现的内容来猜测它正在处理什么{.通常情况下它是正确的,但如果它没有,它将不会意识到一些错误,直到它到达}
举例:
%hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong
%hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right
Run Code Online (Sandbox Code Playgroud)
所以添加+会给你与你给出的第一个例子相同
my %aa = map { +'a'=> 1 } (1..3);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1018 次 |
| 最近记录: |