开发者

PERL Scope in foreach loops

I have a perl scope question.

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";
}

The output I get:

found cycle+1, 1

current=0, nextcycle=0

found cycle+1, 2

current=1, nextcycle=0

found cycle+1, 3

current=2, nextcycle=0

found cycle+1, 4

current=3, nextcycle=0

current=4, nextcycle=0

I expected this:

found cycle+1, 1

current=0, nextcycle=1

found cycle+1, 2

current=1, nextcycle=2

found cycle+1, 3

current=2, nextcycle=3

found cycle+1, 4

current=3, nextcycle=4

current=4, nextcycle=0

I further modified the loop to look like this and got what I wanted:

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 &qu开发者_JS百科ot;found cycle+1, $nextcycle\n";
            last;
        }
    }
    print "current=$cycle, nextcycle=$nextcycle\n";
}

I want to know why the first loop didn't work!


From the Perl manual on the foreach construct:

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.


The scope of the variable in foreach my ... is the foreach loop itself. From perldoc perlsyn:

There is one minor difference: if variables are declared with my in the initialization section of the for, the lexical scope of those variables is exactly the for loop (the body of the loop and the control sections).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜