The while Control Structure
Like most algorithmic programming languages, Perl has a number
of looping structures.[†] The while loop repeats
a block of code as long as a condition is true:
$count = 0;
while ($count < 10) {
$count += 2;
print "count is now $count\n"; # Gives values 2 4 6 8 10
}As always in Perl, the truth value here works like the truth value in the
if test. Also like the if control structure, the block curly braces
are required. The conditional expression is evaluated before the first
iteration, so the loop may be skipped completely if the condition is
initially false.
[†] Every programmer eventually creates an infinite loop by accident. If your program keeps running and running, though, you can generally stop it in the same way you’d stop any other program on your system. Often, typing Control-C will stop a runaway program; check with your system’s documentation to be sure.
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