在"foreach"中确实发生了哪种定位?环形? [英] What kind of localization does occur in a "foreach" loop?

查看:52
本文介绍了在"foreach"中确实发生了哪种定位?环形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有关Foreach循环的主题中,来自perldoc perlsyn :

From perldoc perlsyn on the topic of Foreach Loops:

如果变量以前是用我的声明,它使用变量而不是全局变量,但它仍然位于循环中.

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

似乎这些不是相同的变量.是文档中的错误,还是我什么都没有?

It seems like these are not the same variables. Is it an error in docs, or am I missing anything?

推荐答案

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

Every rule needs its exception, and this is one. In a for loop, if the loop variable is a lexical (declared with my), Perl will create a new lexical aliased to the current item in the loop. The OP code could be written as follows:

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伪代码,为清晰起见修改了答案.

previous example was in Perl pseudocode, answer revised for clarity.

这篇关于在"foreach"中确实发生了哪种定位?环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆