我有一個perl作用域問題。PERL在foreach循環中的作用域
use strict;
use warnings;
our @cycles = (0,1,2,3,4);
foreach my $cycle (@cycles){
my $nextcycle = 0;
foreach $nextcycle (@cycles){
if ($cycle+1 == $nextcycle){
print "found cycle+1, $nextcycle\n";
last;
}
}
print "current=$cycle, nextcycle=$nextcycle\n";
}
輸出I得到:
發現週期+ 1,1
電流= 0,nextcycle = 0
發現週期+ 1,2
電流= 1,nextcycle = 0
found cycle + 1,3
電流= 2,nextcycle = 0
發現週期+ 1,4
電流= 3,nextcycle = 0
電流= 4,nextcycle = 0
我預計此:
找到週期+ 1,1
電流= 0,nextcycle = 1
發現週期+ 1,2
電流= 1,nextcycle = 2
發現週期+ 1,3
電流= 2,nextcycle = 3
發現週期+ 1,4
電流= 3,nextcycle = 4
電流= 4,nextcycle = 0
我進一步修改循環看起來像這一點,得到了我想要的東西:
use strict;
use warnings;
our @cycles = (0,1,2,3,4);
foreach my $cycle (@cycles){
my $nextcycle = 0;
foreach my $tempcycle (@cycles){
if ($cycle+1 == $tempcycle){
$nextcycle = $tempcycle;
print "found cycle+1, $nextcycle\n";
last;
}
}
print "current=$cycle, nextcycle=$nextcycle\n";
}
我想知道爲什麼第一個循環沒有工作!
[Perl的foreach循環的默認範圍是什麼?](http://stackoverflow.com/questions/2238576/what-is-the-default-scope-of-foreach-loop-在-perl的) – mob 2011-03-22 22:42:13