Perl 中 foreach 循环的默认范围是什么? [英] What is the default scope of foreach loop in Perl?

查看:15
本文介绍了Perl 中 foreach 循环的默认范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中,在 foreach 循环中使用 'my' 有什么影响吗?无论是否使用my",索引变量似乎始终是本地的.那么,您能否在 foreach 循环中删除my",而在循环体中仍然具有私有作用域?

In Perl, does using 'my' within a foreach loop have any effect? It seems that the index variable is always local whether or not 'my' is used. So can you drop the 'my' within the foreach loop and still have private scope within the body of the loop?

可以看出,使用 'for' 循环在使用/不使用 'my' 之间是有区别的:

As can be seen, using the 'for' loop there is a difference between using / not using 'my':

use strict; 
use warnings; 

my ($x, $y) = ('INIT', 'INIT'); 

my $temp = 0; 

for ($x = 1; $x < 10; $x++) {
 $temp = $x+1; 
}

print "This is x: $x
";   # prints 'This is x: 10'. 

for (my $y = 1; $y < 10; $y++) {
 $temp = $y+1; 
}

print "This is y: $y
";   # prints 'This is y: INIT'. 

但在 foreach 上似乎没有效果:

But on foreach it does not seem to have an effect:

my ($i, $j) = ('INIT', 'INIT'); 

foreach $i (1..10){
    $temp = $i+1;
}

print "
This is i: $i
";   # prints 'This is i: INIT'. 



foreach my $j (1..10){
    $temp = $j+1;
}

print "
This is j: $j
";   # prints 'This is j: INIT'. 

推荐答案

来自 http://perldoc.perl.org/perlsyn.html#Foreach-Loops:

foreach 循环遍历一个普通的列表值,并依次将变量 VAR 设置为列表的每个元素.如果变量前面有关键字 my,则它是词法范围的,因此仅在循环内可见.否则,该变量是循环的隐式局部变量,并在退出循环时恢复其先前的值.如果变量之前是用 my 声明的,它会使用该变量而不是全局变量,但它仍然本地化到循环中.这种隐式定位只发生在 foreach 循环中.

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. 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. This implicit localisation occurs only in a foreach loop.

这篇关于Perl 中 foreach 循环的默认范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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