我的$ _吗?如果隐含$ _,则执行任何操作 [英] Does my $_; do anything if $_ is implied
问题描述
我认为答案是肯定的,但我只是想确定一下.所以如果我有
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.
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屋!