我的$ _吗?如果隐含$ _,则执行任何操作 [英] Does my $_; do anything if $_ is implied

查看:91
本文介绍了我的$ _吗?如果隐含$ _,则执行任何操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为答案是肯定的,但我只是想确定一下.所以如果我有

I think the answer is yes but I just want to make sure. so if I have

sub something {
    my $_;
    my @array = ...;
    while ( @array ) {
        say;
    }
}

my $_;在使传递给话语的参数词汇化方面实际上有效吗?

is the my $_; actually effective at lexicalizing the parameter passed to the say?

在这种情况下,我使用的是 DZP :: UnusedVarsTests ,它抱怨我没有使用my $_;,并且我怀疑这是一个错误,因为我在暗示的情况下使用了它.

In this particular case I'm using the DZP::UnusedVarsTests and it's complaining that I haven't used my $_; and I suspect it's a bug since I'm using it in a case where it's implied.

推荐答案

简短的回答是是".它使该作用域中的函数使用词法作用域$_,而不是全局$_.如果他们像s///一样写回$_,您将具有一定程度的损害控制.

The short answer is Yes. It makes the functions in that scope use the lexically scoped $_, and not the global $_. If they write back to $_, as in the case of s///, you will have some level of damage control.

每个 perldoc perldelta(5.10.0):

Per perldoc perldelta (5.10.0):

"List::Util::first"在出现词法$_(通常由"my $_"引入或由"given"隐含引入)的情况下发生错误.为每次迭代设置的变量是程序包变量$_,而不是词汇表$_ [RT#67694].

"List::Util::first" misbehaves in the presence of a lexical $_ (typically introduced by "my $_" or implicitly by "given"). The variable which gets set for each iteration is the package variable $_, not the lexical $_ [RT #67694].

类似的问题可能发生在提供以块为第一个参数的函数的其他模块中,例如

A similar issue may occur in other modules that provide functions which take a block as their first argument, like

foo { ... $_ ...} list

并且,在 perldoc perl591delta 中,它继续说:

And, in perldoc perl591delta it goes on to say:

词法$ _

默认变量$_现在可以像下面这样声明了,可以用词法化 任何其他词法变量,带有 简单

Lexical $_

The default variable $_ can now be lexicalized, by declaring it like any other lexical variable, with a simple

     my $_;

$_上默认的操作将使用$_的词法范围版本,而不是全局$_.

The operations that default on $_ will use the lexically-scoped version of $_ when it exists, instead of the global $_.

在"map"或"grep"块中,如果以前对my进行过$_的编写,则该块内的$_也是词法(并作用于该块)

In a "map" or a "grep" block, if $_ was previously my'ed, then the $_ inside the block is lexical as well (and scoped to the block).

$_已被词法化的作用域中,您仍然可以通过使用$::_或更简单地通过用"our $_"覆盖词法声明来访问$_的全局版本.

In a scope where $_ has been lexicalized, you can still have access to the global version of $_ by using $::_, or, more simply, by overriding the lexical declaration with "our $_".

示例

我想提供一些使用此功能的示例:

Examples

I wanted to provide some examples of why this functionality would be used:

my $_ = 'BOOM!';

sub something {
    my $_;                         ## Try running with and without
    my @array = qw/foo bar baz/;
    while ( $_ = pop @array ) {
        say;
    }   
}   

something();

say;

还有另一个例子

my $_ = 'foo';

sub something {
  my $_ = $_;  ## Try running with and without
  s/foo/bar/;
  $_;
}

something();

say;

这篇关于我的$ _吗?如果隐含$ _,则执行任何操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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