为什么这个地图块含有一个显然没用的? [英] Why does this map block contain an apparently useless +?
问题描述
浏览源代码时,我看到以下行:
While browsing the source code I saw the following lines:
my @files_to_keep = qw (file1 file2);
my %keep = map { + $_ => 1 } @files_to_keep;
在此代码中 +
做了什么片段?我使用 Data :: Dumper
查看是否取出加号做任何事情,但结果是一样的:
What does the +
do in this code snippet? I used Data::Dumper
to see whether taking out the plus sign does anything, but the results were the same:
$ perl cleanme.pl
$VAR1 = {
'file1' => 1,
'file2' => 1
};
推荐答案
这用于防止解析问题。加号表示解释器的行为就像一个正常的块,而不是一个表达式。
This is used to prevent a parsing problem. The plus symbol forces the interpreter to behave like a normal block and not an expression.
恐怕是你可能试图使用其他(表达式)创建一个散列引用,
The fear is that perhaps you are trying to create a hashreference using the other (expression) formulation of map
like so.
@array_of_hashrefs = map { "\L$_" => 1 }, @array
注意逗号。那么如果解析器猜测你在OP中给出了这个语句,那么会出现一个缺少逗号的语法错误!要看到区别,请引用$ _
。无论什么原因,解析器都足以触发表达式行为。
Notice the comma. Then if the parser guesses that you are doing this given the statement in the OP there will a syntax error for missing the comma! To see the difference try quoting "$_"
. For whatever reason, the parser takes this as enough to trigger the expression behavior.
是的,它是一个奇怪的。因此,许多超级偏执的Perl程序员比需要多加多余的加号(我包括)。
Yes its an oddity. Therefore many extra-paranoid Perl programmers toss in the extra plus sign more often than needed (me included).
以下是 地图
文档。
Here are the examples from the map
documentation.
%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
For a fun read (stylistically) and a case where the parser gets it wrong read this: http://blogs.perl.org/users/tom_wyant/2012/01/the-case-of-the-overloaded-curlys.html
这篇关于为什么这个地图块含有一个显然没用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!