gpt4 book ai didi

perl - 为什么这个 map block 包含一个明显没用的+?

转载 作者:行者123 更新时间:2023-12-04 01:47:10 25 4
gpt4 key购买 nike

在浏览源代码时,我看到了以下几行:

my @files_to_keep = qw (file1 file2);
my %keep = map { + $_ => 1 } @files_to_keep;
+ 有什么用在这个代码片段中做什么?我用过 Data::Dumper看看去掉加号是否有什么作用,但结果是一样的:
  $ perl cleanme.pl
$VAR1 = {
'file1' => 1,
'file2' => 1
};

最佳答案

这用于防止解析问题。加号强制解释器表现得像一个普通块而不是一个表达式。

担心的是,您可能正在尝试使用 map 的其他(表达式)公式来创建哈希引用。像这样。

@array_of_hashrefs = map {  "\L$_" => 1  }, @array

注意逗号。然后,如果解析器根据 OP 中的语句猜测您正在执行此操作,则会出现缺少逗号的语法错误!要查看差异,请尝试引用 "$_" .无论出于何种原因,解析器都认为这足以触发表达式行为。

是的,它很奇怪。因此,许多偏执的 Perl 程序员比需要的更频繁地添加额外的加号(包括我在内)。

以下是来自 map 的示例文档。
%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 { lc($_) => 1 } @array # as does this.
%hash = map +( lc($_) => 1 ), @array # this is EXPR and works!
%hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)

对于有趣的阅读(风格上)和解析器出错的情况,请阅读: http://blogs.perl.org/users/tom_wyant/2012/01/the-case-of-the-overloaded-curlys.html

关于perl - 为什么这个 map block 包含一个明显没用的+?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277284/

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