While Loop

While loop

While statement is a Perl control structure which allows you to execute a block of code repeatedly. the while statement is used when you want to check condition before make a loop. Here is the while statement syntax:

  1. while(condition){
  2.   #statements;
  3. }

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.

  1. $x = 0;
  2. while($x < 5){
  3.   print "$x\n";
  4.   $x++;
  5. }

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:

  1. $x = 0;
  2. do{
  3.   print "$x\n";
  4.   $x++;
  5. }while($x < 5);

First the 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 reach 5.