gpt4 book ai didi

perl - 在 "foreach"循环中会发生什么样的定位?

转载 作者:行者123 更新时间:2023-12-05 00:42:17 26 4
gpt4 key购买 nike

来自 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

似乎这些不是相同的变量。这是文档中的错误,还是我遗漏了什么?

最佳答案

每条规则都需要异常(exception),这就是异常(exception)。在 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
}

编辑:前面的例子是 Perl 伪代码,为清楚起见修改了答案。

关于perl - 在 "foreach"循环中会发生什么样的定位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2247963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com