加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – “foreach”循环中发生了什么样的本地化?

发布时间:2020-12-16 06:21:55 所属栏目:大数据 来源:网络整理
导读:来自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
来自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
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读