什么是“%_"?在Perl中? [英] What is "%_" in perl?

查看:124
本文介绍了什么是“%_"?在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆