Consider the standard while loop:
initialization code
while ( Test code ) {
Code to execute in body
} continue {
Update code
} |
This can be generalized into the concise for loop:
for ( initialization code; test code; update code ) {
body code
} |
When the loop is first entered, the code at initialization is executed. Each time through the loop, the test at test is executed and the loop stops if it returns false. After the execution of each loop, the code at update is performed.
Compare the process of counting from 1 to 5:
# with a while loop
$count = 1;
while ( $count <= 5 ) {
print $count,"\n";
} continue {
$count++;
}
# with a for loop
for ( my $count=1; $count<=5; $count++ ) {
print $count,"\n";
} |
Notice how we use my to make $count local to the for loop.
Any of the three for components are optional. You can even leave them all off to get an infinite loop:
for (;;) {
print "Somebody help me! I can't stop!\n";
}
# equivalent to:
while (1) {
print "Somebody help me! I can't stop!\n";
} |
Any of the components can be a list. This is usually used to initialize several variables at once:
# read until the "end" line or 10 lines, whichever
# comes first....
for (my $done=0,my $i=1; $i<10 and !$done; $i++) {
my $line = <STDIN>;
chomp $line;
$done++ if $line eq 'end';
} |
|
| Contents |
Next |