perl - 我的 $_;如果 $_ 是隐含的,则做任何事情

标签 perl lexical-scope

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

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 simple

     my $_;

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 previously my'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/

相关文章:

perl - 访问 WWW::Mechanize 响应的首选方法是什么?

c# - lambda 中的 Alpha 转换

scipy - 为什么 COBYLA 不尊重约束?

perl - 如何将 @ARGV 的元素分配给 $variable,然后打印它?

perl - 加载特定版本的 perl 模块

regex - sed regex 在第一场比赛时停止

perl - 使用 perl 的 Wordnet 同义词集

r - 您能让 R 函数在求值时查看其自身形式的值吗?

language-agnostic - 为什么我有时会听到 "lexical variable?"这个词