Looping Constructs
These statements allow a Perl program to repeatedly execute the same code, so they are often known as iterative constructs. There are several kinds, which differ primarily in how you know when you’re done with the loop and can go on to other things.
Conditional loops
The while and until statements test an expression for truth just as the if and unless statements do, except that they’ll
execute the block repeatedly as long as the condition is satisfied
each time through. The condition is always checked before each
iteration. If the condition is met (that is, if it is true for a
while or false for an until), the block of the statement is
executed.
print "How many tickets have we sold so far? ";
my $before = <STDIN>;
my $sold = $before;
while ($sold < 10000) {
my $available = 10000 – $sold;
print "$available tickets are available. How many would you like: ";
my $purchase = <STDIN>;
if ($purchase > $available) {
say "Too many! Try again.";
$purchase = 0;
}
$sold += $purchase;
}
say "This show is sold out, please come back later.";Note that if the original condition is never met, the loop will never be entered at all. For example, if we’ve already sold 10,000 tickets, we will report the show to be sold out immediately.
In our Average Example earlier, line 8 reads:
while (my $line = <GRADES>) {This assigns the next line to the variable $line and, as we explained earlier, returns
the value of $line so that the
condition of the while statement
can evaluate $line for truth. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access