微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Perl中foreach循环的默认范围是多少?

在Perl中,在foreach循环中使用’my’有什么作用吗?似乎索引变量始终是本地的,不管是否使用’my’.那么你可以在foreach循环中放置’我的’,并且在循环体内仍然有私有的范围?

可以看出,使用’for’循环使用/不使用’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\n";   # prints 'This is x: 10'. 

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

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

但是在foreach它似乎没有效果

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

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

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



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

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

解决方法

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

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐