我认为答案是肯定的,但我只是想确定一下。所以如果我有
sub something {
my $_;
my @array = ...;
while ( @array ) {
say;
}
}
是
my $_;
实际上有效地对传递给 say 的参数进行词法化?在这种特殊情况下,我使用的是 DZP::UnusedVarsTests它提示我没有用过
my $_;
我怀疑这是一个错误,因为我在暗示它的情况下使用它。
最佳答案
简短的回答是肯定的。它使该作用域内的函数使用词法作用域 $_
,而不是全局 $_
.如果他们回信 $_
,如 s///
的情况,您将有一定程度的损坏控制。
每 perldoc perldelta
(5.10.0) :
"
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
它接着说:Lexical $_
The default variable
$_
can now be lexicalized, by declaring it like any other lexical variable, with a simplemy $_;
The operations that default on
$_
will use the lexically-scoped version of$_
when it exists, instead of the global$_
.In a "
map
" or a "grep
" block, if$_
was previouslymy
'ed, then the$_
inside the block is lexical as well (and scoped to the block).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 $_
".
例子
我想提供一些示例,说明为什么要使用此功能:
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;
关于perl - 我的 $_;如果 $_ 是隐含的,则做任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3393038/