login

Perl While Loop

Summary: In this tutorial, you will learn another control flow statement called Perl while loop to execute a piece of code in a number of times based on a specific boolean condition.

Perl While loop

Perl While statement is a Perl control structure that allows to execute a block of code repeatedly. The Perl while statement is used when you want to check a boolean condition before making a loop.

The following illustrates the Perl while statement syntax:

 while(condition){
   #statements;
 }

The statements will be executed as long as the logical expression between the parentheses is true. Because the condition is checked before making iteration so if the condition is initially false, the statements inside the will not executed at all. It is a very important to update the the condition in the while loop body to avoid an indefinite loop. Here is a code snippet to demonstrate while statement.

$x = 0;

while($x < 5){
  print "$x\n";
  $x++;
}

First we set variable $x with 0. Next in the while loop condition we checked whether $x less than or not. Then we printed value of $x on screen and inside while loop body we increase $x by 1. The iteration repeatedly until $x value reaches 5.

Loop with do while

Beside while loop, Perl also provides do while loop statement. do while loop statement is similar to while loop but it checks the loop condition after executing the block therefore block executes at least one time. Here is a code snippet to demonstrate do while statement:

$x = 0;

do{
  print "$x\n";
  $x++;
}while($x < 5);

It first prints $x value, next it increases $x by 1. The do while checks whether the $x less than 5 or not, if not it executes the block again until $x reaches 5.