Looping
A
Looping constructs (also known as for
, foreach
, while
, and until
.
for
The for
construct performs a statement (block of code) for a set of conditions defined as follows:
for (
}
The start condition is set at the beginning of the loop. Each time the loop is executed, the increment function is performed until the end condition is achieved. This looks much like the traditional for/next
loop. The following code is an example of a for
loop:
for ($i=1; $i<=10; $i++) {
print '$i
'
}
foreach
The foreach
construct performs a statement block for each element in a list or array:
@names = ('alpha','bravo','charlie');
foreach $name (@names) {
print '$name sounding off!
';
}
The loop variable ($name
in the example) is not merely set to the value of the array elements; it is aliased to that element. That means if you modify the loop variable, you're actually modifying the array. If no loop array is specified, the Perl default variable $_
may be used:
@names = ('alpha','bravo','charlie');
foreach (@names) {
print '$_ sounding off!
';
}
This syntax can be very convenient, but it can also lead to unreadable code. Give a thought to the poor person who'll be maintaining your code. (It will probably be you.)
foreach
is frequently abbreviated as for
.
while
while
performs a block of statements as long as a particular condition is true:
while ($x<10) {
print '$x
';
$x++;
}
Remember that the condition can be anything that returns a true or false value. For example, it could be a function call:
while ( InvalidPassword($user, $password) ) {
print 'You've entered an invalid password. Please try again.
';
$password = GetPassword;
}
until
until
is the exact opposite of the while
statement. It performs a block of statements as long as a particular condition is false — or, rather, until it becomes true:
until (ValidPassword($user, $password)) {
print 'You've entered an invalid password. Please try again.
';
$password = GetPassword;
}
last
and next
You can force Perl to end a loop early by using a last
statement. last is similar to the C break
command—the loop is exited. If you decide you need to skip the remaining contents of a loop without ending the loop itself, you can use next
, which is similar to the C continue
command. Unfortunately, these statements don't work with do ... while
.
On the other hand, you can use redo
to jump to a loop (marked by a label) or inside the loop where called:
$a = 100; while (1) {
print 'start
';
TEST: {
if (($a = $a / 2) > 2) {
print '$a
';
if (--$a < 2) {
exit;
}
redo TEST;
}
}