在"foreach"循环中发生了什么样的本地化?

Eug*_*ash 4 perl scope localization

来自perldoc perlsyn关于Foreach循环的主题:

如果先前使用my声明了变量,它将使用该变量而不是全局变量,但它仍然本地化为循环.

但请考虑这个例子:

use Devel::Peek;
my $x = 1;
Dump $x;
for $x ( 1 ) { Dump $x }

SV = IV(0x8117990) at 0x8100bd4
  REFCNT = 1
  FLAGS = (PADBUSY,PADMY,IOK,pIOK)
  IV = 1
SV = IV(0x8117988) at 0x8100bf8
  REFCNT = 2
  FLAGS = (IOK,READONLY,pIOK)
  IV = 1
Run Code Online (Sandbox Code Playgroud)

看起来这些变量并不相同.这是文档中的错误,还是我错过了什么?

Eri*_*rom 5

每个规则都需要它的例外,这是一个.在for循环中,如果循环变量是词法(声明为my),Perl将为循环中的当前项创建一个新的词法别名.OP代码可以写成如下:

use Data::Alias 'alias';

my $x = 1;
for (2..3) {
    alias my $x = $_;
    # note that $x does not have dynamic scope, and will not be visible in 
    # subs called from within the loop
    # but since $x is a lexical, it can be closed over
}
Run Code Online (Sandbox Code Playgroud)

编辑:上一个例子是在Perl伪代码中,为了清晰起见,修改了答案.