gpt4 book ai didi

perl - 为什么Perl函数 "map"给出错误 "Not enough arguments for map"

转载 作者:行者123 更新时间:2023-12-04 04:57:08 29 4
gpt4 key购买 nike

这是我不明白的事情。

该脚本可以正常工作(请注意 map 功能中的串联):

#!/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
};

但是,如果没有串联,该 map 将无法正常工作。这是我希望可以使用的脚本,但它不能:
#!/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;

因为尽管“{”通常是块的开始,但它也可能是hashref的开始。

这些启发式方法在 token 流(IIRC两个 token )中并不遥远。

您可以使用以下命令强制将“{”解释为一个块:
map {; STATEMENTS } LIST;    # the semicolon acts as a disambigator

您可以使用以下命令强制将“{”解释为哈希值:
map +{ LIST }, LIST;    # the plus sign acts as a disambigator
grep也遭受类似的痛苦。 ( do在技术上也是如此,因为可以将hashref用作参数,然后将其字符串化并当作文件名来对待。这虽然很奇怪。)

关于perl - 为什么Perl函数 "map"给出错误 "Not enough arguments for map",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21032709/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com