Perl until Loop



An until loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is false.

Syntax

The syntax of an until loop in Perl programming language is −

until(condition) {
   statement(s);
}

Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates until the condition becomes true. When the condition becomes true, the program control passes to the line immediately following the loop.

The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value.

Flow Diagram

until loop in Perl

Here key point of the until loop is that the loop might not ever run. When the condition is tested and the result is true, the loop body will be skipped and the first statement after the until loop will be executed.

Example

#!/usr/local/bin/perl
 
$a = 5;

# until loop execution
until( $a > 10 ) {
   printf "Value of a: $a\n";
   $a = $a + 1;
}

Here we are using the comparison operator > to compare value of variable $a against 10. So until the value of $a is less than 10, until loop continues executing a block of code next to it and as soon as the value of $a becomes greater than 10, it comes out. When executed, above code produces the following result −

Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
Value of a: 9
Value of a: 10
perl_loops.htm
Advertisements