Loops
while (condition) {
instructions
.
.
.
}
- Everything within the curly braces ("{ }") is executed from
zero to an infinite number of times.
#!perl
$x = 0;
while ($x < 10) {
print "The value of x is: $x\n";
$x++;
}
print "All done. The value of x is now: $x\n";
- How it works:
- condition is some
sort of comparision: for example, $x < 10 (value of $x less
than 10.)
- The condition is tested by the while statement.
- When Perl gets to the while,she
examines the condition. "Is
the value of variable $x less than 10 right now?" she
asks.
- If $x is less than 10 right now, Perl then runs the
instructions between the curly braces.
- When Perl sees the closing brace ("}") she goes back up to
the while statement.
- If $x is not less than 10 right now (in other words, if it is
equal to or greater than 10), Perl skips all of the instructions
between the curly braces and executes the next instruction after the
closing brace.
The value of x is: 0
The value of x is: 1
The value of x is: 2
The value of x is: 3
The value of x is: 4
The value of x is: 5
The value of x is: 6
The value of x is: 7
The value of x is: 8
The value of x is: 9
All Done. The value of x is now: 10
print "You must be at least 15 years old...\n";
@ages = (10, 12, 12, 14, 15, 17, 18);
foreach $age (@ages) {
print "You're $age... "
if ($age >= 15) {
print "that's old enough.\n";
}
else {
print "that's not old enough.\n";
}
}