do until loop - Beginning Perl Tutorial, Control Structures

How to use a do until loop in Perl

Man working on laptop
Yula/E+/Getty Images

Perl's do .. until loop is almost exactly the same as the until 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 until a specific condition is evaluated as true. It is the logical opposite of the do .. while loop.

 do {
 ...
 } until (expression); 
Perl starts by executing the code inside the do .. until block, then the expression inside the parenthesis is evaluated.
If the expression evaluates as false the code is executed again, and will continue to execute in a loop until the expression evaluates as true. Let's look at an example of Perl's do .. until loop in action and break down exactly how it works, step by step.
 $count = 10;
 do {
 print "$count ";
 $count--;
 } until ($count == 0);
 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 .. until loop, and the code inside the block is executed. Next, the expression in the parenthesis is evaluated:
 until ($count == 0) 
If the until expression is evaluated as false, the code inside the block is executed again and the expression is re-evaluated. When it finally evaluates as true, the rest of the Perl script is executed.
  1. $count is set to a value of 10.
  1. Execute the code block inside the do .. until loop.
  2. Is $count is equal to 0? If not, repeat the do .. until loop, otherwise exit the do .. until 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 until $count has a value equal to 0, at which point the loop stops and the word 'Blastoff' is printed.
  1. A do .. until loop is a Perl control structure.
  1. It is used to step through a block of code until a specific condition is true, but executes the code before evaluating the expression.
Format
mla apa chicago
Your Citation
Brown, Kirk. "do until loop - Beginning Perl Tutorial, Control Structures." ThoughtCo, Nov. 25, 2014, thoughtco.com/do-until-loop-beginning-control-structures-2641139. Brown, Kirk. (2014, November 25). do until loop - Beginning Perl Tutorial, Control Structures. Retrieved from https://www.thoughtco.com/do-until-loop-beginning-control-structures-2641139 Brown, Kirk. "do until loop - Beginning Perl Tutorial, Control Structures." ThoughtCo. https://www.thoughtco.com/do-until-loop-beginning-control-structures-2641139 (accessed September 21, 2017).