当我重新声明Perl foreach控制变量时,为什么不收到警告?

10 variables perl warnings

为什么$i在以下代码中没有重新声明的警告?

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

for my $i (1..3) {
  my $i = 'DUMMY';
  print Dumper $i;
}
Run Code Online (Sandbox Code Playgroud)

wil*_*ert 9

实际上,您只会在同一范围内收到重新定义的警告.写作:

use warnings;
my $i;
{
  my $i;
  # do something to the inner $i
}
# do something to the outer $i
Run Code Online (Sandbox Code Playgroud)

完全有效.

我不确定Perl内部是否以这种方式处理它,但您可以将您的for循环视为被解析为

{
  my $i;
  for $i ( ... ) { ... }
  # the outer scope-block parens are important!
};
Run Code Online (Sandbox Code Playgroud)


Eug*_*ash 2

如果您在当前作用域或语句中重新声明my,our或变量,您将收到警告。state第一个$i实际上不是词汇变量。您可以使用以下方法证明这一点Devel::Peek

use Devel::Peek;   

for my $i (1) {
    Dump $i;
}  

SV = IV(0x81178c8) at 0x8100bf8
REFCNT = 2
FLAGS = (IOK,READONLY,pIOK)
IV = 1
Run Code Online (Sandbox Code Playgroud)

FLAGS 中没有PADMY标志,这表明它$i是一个词法变量,用 声明my