相关疑难解决方法(0)

Perl中foreach循环的默认范围是什么?

在Perl中,在foreach循环中使用'my'会产生什么影响吗?无论是否使用'my',索引变量似乎始终是本地的.那么你可以在foreach循环中删除'my'并且仍然在循环体内有私有范围吗?

可以看出,使用'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'. 
Run Code Online (Sandbox Code Playgroud)

但是在foreach上它似乎没有效果:

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

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

print …
Run Code Online (Sandbox Code Playgroud)

perl foreach scope

16
推荐指数
3
解决办法
3665
查看次数

标签 统计

foreach ×1

perl ×1

scope ×1