Chapter 10. Loops
A loop is a block of code the iterates (repeats) a list of commands as long
as the loop control condition is true.
while loops
The statements within a while block are repeated as long as the condition remains
true. In this case, printing the value of $start and then decrementing it by one.
while (condition) {
command
}
$start = 5;
while ($start > 0) {
print "$start... ";
--$start
}
print "BOOM\n";
|
until loops
The statements within the until block are repeated al long as the condition remains
false. In this case, printing the value of $start and decrimenting it by one.
until (condition) {
command
}
$start = 5;
until ($start <= 0) {
print "$start... ";
--$start
}
print "BOOM\n";
|
do loop
With a while block, if the condition is false from the start, Perl will never get to
the statements inthe block. If you want Perl to execute the statements at least once,
you can use a do block.
do {
command
} while (condition)
$start = 5;
do {
print "$start... ";
--$start;
} while ($start < 0);
print "BOOM\n";
|
You can also use until instead of while, depending on wether you want to test if
the condition is false or true.
for loops
The for conditional makes it easy to repeat a block a given number of times by
following the progress of a counter - a variable whose sole purpose in life is to
count how many times the block has been executed. You first must set the the initial
state of the counter, then decide what condition should cause the statement to stop
being executed, and then set the way the counter will be incremented.
for ( $i=1; condition; $i++) {
statement(s)
}
$start = 5;
for ( $i = $start; $i > 0; --$i) {
print "$i... ";
}
print "BOOM\n";
|
The block executes the statements for each value of $i until the condition is
false.
foreach loops
Perl has a special construction that lets you execute a block of statements for each
element of an array. It's called foreach.
foreach $element (@array) {
statement(s)
}
$name = "Kat";
@prey=("mouse","bird","gopher");
foreach $creature (@prey) {
print "$name likes to eat $creature\n";
}
|
|