As we've discussed, Perl's while loop is used to loop through a designated block of code
while a specific condition is evaluated as true. Let's look at an example of Perl's while loop in action and break down exactly how it works, step by step.
$count = 10;
while ($count >= 1) {
print "$count ";
$count--;
}
print "Blastoff.\n";
Running this simple Perl script produces the following output:
10 9 8 7 6 5 4 3 2 1 Blastoff.
First we set the string
$count to a value of 10.
$count = 10;
Next comes the start of the
while loop, and the expression in the parenthesis is evaluated:
while ($count >= 1)
If the while expression is evaluated as
true, the code inside the block is executed and the expression is re-evaluated. When it finally evaluates as
false, the block is skipped and the rest of the Perl script is executed.
- $count is set to a value of 10.
- Is $count greater than or equal to 1? If so, continue, otherwise exit the while loop.
- Execute the code block inside the while loop.
- Return to step 2.
The end result is that $count starts at 10 and comes down by 1 every time the loop is executed. When we print the value of $count, we can see that the loop is executed
while $count has a value of
greater than or equal to 1, at which point the loop stops and the word 'Blastoff' is printed.
- A while loop is a Perl control structure.
- It is used to step through a block of code while a specific condition is true.
Previous:
How to use a while loop in Perl