while loop - Beginning Perl Tutorial, Control Structures

How to use a While Loop in Perl

Focused female hacker wearing baseball cap working hackathon at laptop in workshop
Hero Images / Getty Images

Perl's while loop, is used to loop through a designated block of code while a specific condition is evaluated as true.

 while (expression) {
 	...
 } 

Perl starts the block by evaluating the expression inside the parenthesis. If the expression evaluates as true the code is executed, and will continue to execute in a loop until the expression evaluates as false. If the expression initially evaluates to false, the code is never executed and the while block will be skipped entirely.

The while loop process looks something like this when you break down each of the steps:

  1. Evaluate the initial expression.
  2. Does the test evaluate to true? If so, continue, otherwise exit the while loop.
  3. Execute the code block inside the while loop.
  4. Return to step 2.

Unlike the for loop, the while loop does not have a self-contained way to alter the initial expression. Be careful that your Perl script does not wind up in a continuous while loop and lock up or crash.

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.

  1. $count is set to a value of 10.
  2. Is $count greater than or equal to 1? If so, continue, otherwise exit the while loop.
  3. Execute the code block inside the while loop.
  4. 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.

  1. A while loop is a Perl control structure.
  2. It is used to step through a block of code while a specific condition is true.