while and until Loops
A while loop repeats its block as long as a condition is true. Its mirror image, until, repeats until a condition becomes true.
while
use strict;
use warnings;
my $balance = 1000;
my $year = 0;
while ($balance < 1500) {
$balance *= 1.08; # 8% interest per year
$year++;
}
printf "After %d years the balance is %.2f\n", $year, $balance;After 6 years the balance is 1586.87
The condition is checked before each pass, so if it is false from the start the body never runs.
until
until (COND) is the same as while (!COND). Choose whichever reads more naturally:
use strict;
use warnings;
my $countdown = 5;
until ($countdown == 0) {
print "$countdown... ";
$countdown--;
}
print "liftoff!\n";5... 4... 3... 2... 1... liftoff!
Looping over a queue
while pairs nicely with shift, which returns undef (false) once the array is empty. Here a task queue is processed until nothing is left, and new work can be added along the way:
use strict;
use warnings;
my @queue = ("download", "unzip");
while (defined(my $job = shift @queue)) {
print "Running $job\n";
push @queue, "cleanup" if $job eq "unzip";
}
print "Queue empty\n";Running download
Running unzip
Running cleanup
Queue empty
The defined(...) matters when the queue might contain false values like 0 or "": without it, the loop would stop early at such an element.
Reading lines with while
The most important while loop in Perl reads input line by line. <$fh> returns the next line, or undef at the end of the input. Here the input is a string opened as an in-memory filehandle (the file I/O lesson explains this):
use strict;
use warnings;
my $text = "alpha\nbeta\ngamma\n";
open my $fh, '<', \$text or die "Cannot open: $!";
my $line_no = 0;
while (my $line = <$fh>) {
chomp $line; # remove the trailing newline
$line_no++;
print "$line_no: $line\n";
}
close $fh;1: alpha
2: beta
3: gamma
while (my $line = <$fh>) is so common that Perl automatically wraps it in defined(...), so a last line containing just 0 is not lost.
Postfix while and do-while
A while can also be a statement modifier. To run a body at least once, use do { ... } while (...):
use strict;
use warnings;
my $n = 1;
$n *= 2 while $n < 100;
print "First power of two >= 100: $n\n";
my $attempt = 0;
do {
$attempt++;
print "Attempt $attempt\n";
} while ($attempt < 3);First power of two >= 100: 128
Attempt 1
Attempt 2
Attempt 3
Note:
do { } whileis not a real loop block, solastandnextdo not work inside it. Prefer a plainwhilewhen you need loop control.
Infinite loops
while (1) { ... } loops forever until something inside calls last (covered in the loop-control lesson). Make sure every loop has a way to end; on this site a runaway program is stopped by a time limit.
Test yourself
When is the condition of a while loop checked?
- After each pass
- Before each pass
- Only once
- Only at the end
until ($done) { ... } is equivalent to:
while ($done) { ... }while (!$done) { ... }if (!$done) { ... }for ($done) { ... }
Which construct always runs its body at least once?
while (...) { }until (...) { }do { } while (...)for (...) { }