来自perldoc
perlsyn关于Foreach循环的主题:
If the variable was prevIoUsly
declared with my,it uses that
variable instead of the global one,
but it’s still localized to the loop.
但请考虑这个例子:
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
看起来这些变量并不相同.这是文档中的错误,还是我错过了什么?
解决方法
每个规则都需要它的例外,这是一个.在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 }