Loops let you execute the same statements over and over again.
A while loop has a condition at the top. The code within the body will execute until the code becomes false.
while ( TEST ) {
Code to execute
} continue {
Optional code to execute at the end of each loop
} |
Code:
#!/usr/local/bin/perl
# file: spud_counter.pl
$count = 0;
while ( $word = shift ) { # read from command line
if ($word eq 'potato') {
print "Found a potato!\n";
$count++;
} else {
print "$word is not a potato\n";
}
}
print "Potato count: $count\n"; |
Output:
(~) 51% spud_counter.pl potato potato tomato potato boysenberry Found a potato! Found a potato! tomato is not a potato Found a potato! boysenberry is not a potato Potato count: 3
Code:
#!/usr/local/bin/perl
# file: count_up.pl
$count = 1;
while ( $count <= 5 ) {
print "count: $count\n";
$count++;
} |
Output:
(~) 51% count_up.pl count: 1 count: 2 count: 3 count: 4 count: 5
Code:
#!/usr/local/bin/perl
# file: count_down.pl
$count = 6;
while ( --$count > 0 ) {
print "count: $count\n";
} |
Output:
(~) 51% count_down.pl count: 5 count: 4 count: 3 count: 2 count: 1
while loops can have an optional continue block containing code that is executed at the end of each loop, just before jumping back to the test at the top:
#!/usr/local/bin/perl
# file: count_up.pl
$count = 1;
while ( $count <= 5 ) {
print "count: $count\n";
} continue {
$count++;
} |
continue blocks will make more sense after we consider loop control variables.
Sometimes you want to loop until some condition becomes true, rather than until some condition becomes false. The until loop is easier to read than the equivalent while (!TEST).
my $counter = 5;
until ( $counter < 0 ) {
print $counter--,"\n";
} |
foreach will process each element of an array or list:
foreach $loop_variable ('item1','item2','item3') {
print $loop_variable,"\n";
}
@array = ('item1','item2','item3');
foreach $loop_variable (@array) { # same thing, but with an array
print $loop_variable,"\n";
}
@array = ('item1','item2','item3');
foreach (@array) { # same difference
print $_,"\n";
} |
The last example is interesting. It shows that if you don't explicitly give foreach a loop variable, the special scalar variable $_ is used.
If you modify the loop variable in a foreach loop, the underlying array value will change!
Code:
@h = (1..5); # make an array containing numbers between 1 and 5
foreach $variable (@h) {
$variable .= ' potato';
}
print join("\n",@h),"\n"; |
Output:
1 potato 2 potato 3 potato 4 potato 5 potato
This works with the automatic $_ variable too:
Code:
@h = ('CCCTTT','AAAACCCC','GAGAGAGA');
foreach (@h) {
($_ = reverse $_) =~ tr/GATC/CTAG/;
} |
|
| Contents |
Next |