Perl Tutorial Perl References

Perl - Until Loop



The Until Loop

Until loop allows a set of statements to be executed repeatedly as long as a specified condition is false. The program exits from the until loop when the given condition becomes true. The syntax for using until statement is given below:

Syntax

until (condition) {
  statements;
}

Flow Diagram:

Perl Until Loop

In the below mentioned example, program keeps on printing the variable i until it becomes 10.

$i = 1;
until ($i == 10){
  print("i = $i \n");
  $i++;
}

The output of the above code will be:

i = 1 
i = 2 
i = 3 
i = 4 
i = 5 
i = 6 
i = 7 
i = 8 
i = 9 

Consider one more example where the until loop is used to sum all natural numbers from 1 to 10.

$i = 1;
$sum = 0;

until ($i > 10){
  $sum = $sum + $i;
  $i++;
}

print("sum = $sum \n");

The output of the above code will be:

sum = 55