什么是“%_"?在 perl 中? [英] What is "%_" in perl?
问题描述
我刚刚得到了一个代码片段:
I've just been given a code snippet:
@list = grep { !$_{$_}++ } @list;
作为重复数据删除的惯用语.它似乎有效,但是 - perlvar
中没有列出 %_
.
As an idiom for deduplication. It seems to work, but - there's no %_
listed in perlvar
.
我通常会通过声明 %seen
来编写上述内容,例如:
I'd normally be writing the above by declaring %seen
e.g.:
my %seen; my @list = grep { not $seen{$_}++ } @list;
但是 %_
似乎有效,尽管它似乎是全局范围.谁能指出我的参考资料?(或者至少让我放心,执行上述操作不会破坏某些重要的东西!)
But %_
seems to work, although it seems to be global scope. Can anyone point me to a reference for it? (Or at least reassure me that doing the above isn't smashing something important!)
推荐答案
这是一个散列.您可以使用名为 _
的哈希,因为 _
是变量的有效名称.(我确定您熟悉 $_
和 @_
.)
It's a hash. You can have a hash named _
because _
is a valid name for a variable. (I'm sure you are familiar with $_
and @_
.)
目前没有 Perl 内置程序设置它或隐式读取 %_
,但保留标点变量,例如 %_
.
No Perl builtin currently sets it or reads %_
implicitly, but punctuation variables such as %_
are reserved.
Perl 变量名也可以是数字序列或单个标点符号或控制字符(不推荐使用文字控制字符形式).这些名称都是 Perl 为特殊用途保留的
Perl variable names may also be a sequence of digits or a single punctuation or control character (with the literal control character form deprecated). These names are all reserved for special uses by Perl
<小时>
请注意,标点变量也很特殊,因为它们是超级全局变量".这意味着不合格的%_
指的是根包中的%_
,而不是当前包中的%_
.
Note that punctuation variables are also special in that they are "super globals". This means that unqualified %_
refers to %_
in the root package, not %_
in the current package.
$ perl -E'
%::x = ( name => "%::x" );
%::_ = ( name => "%::_" );
%Foo::x = ( name => "%Foo::x" );
%Foo::_ = ( name => "%Foo::_" );
package Foo;
say "%::x = $::x{name}";
say "%::_ = $::_{name}";
say "%Foo::x = $Foo::x{name}";
say "%Foo::_ = $Foo::_{name}";
say "%x = $x{name}";
say "%_ = $_{name}";
'
%::x = %::x
%::_ = %::_
%Foo::x = %Foo::x
%Foo::_ = %Foo::_
%x = %Foo::x
%_ = %::_ <-- surprise!
这意味着忘记使用local %_
(正如您所做的那样)会产生非常深远的影响.
This means that forgetting to use local %_
(as you did) can have very far-reaching effects.
这篇关于什么是“%_"?在 perl 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!