do while loop - Beginning Perl Tutorial, Control Structures

How to use a do while loop in Perl

Man using laptop
Noel Hendrickson/Photodisc/Getty Images

Perl's do .. while loop is almost exactly the same as the while loop with one crucial difference—the code is executed before the expression is evaluated. It is used to loop through a designated block of code while a specific condition is evaluated as true.

 do {
} while (expression); 

Perl starts by executing the code inside the do .. while block, then the expression inside the parenthesis is evaluated. If the expression evaluates as true, the code is executed again and will continue to execute in a loop until the expression evaluates as false. 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;
do {
print "$count ";
} while ($count >= 1);
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 do .. while loop, and the code inside the block is executed. Next, 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 again and the expression is re-evaluated. When it finally evaluates as false, the rest of the Perl script is executed.

  1. $count is set to a value of 10.
  2. Execute the code block inside the do .. while loop.
  3. Is $count greater than or equal to 1? If so, repeat the do .. while loop, otherwise exit the do .. while loop.

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 do .. while loop is a Perl control structure.
  2. It is used to step through a block of code while a specific condition is true, but executes the code before evaluating the expression.