Perl Tutorial Perl References

Perl - Redo Statement



The redo statement in Perl is used to repeat the current iteration of the loop. It is always used inside the loop. It restarts the loop without checking loop condition.

Redo statement with While loop

In the example below, the redo statement is used to skip the while loop if the value of variable i becomes 5.

$restart = 1;
$i = 1;

#using redo inside while loop
while($i <= 10){
  if($i == 5 && $restart == 1) {
    print("Repeating loop when i = $i \n");
    $restart = 0;

    #using redo statement
    redo;
  }
  print("i = $i \n");
  $i++;
}

The output of the above code will be:

i = 1 
i = 2 
i = 3 
i = 4 
Repeating loop when i = 5 
i = 5 
i = 6 
i = 7 
i = 8 
i = 9 
i = 10 

Redo statement with For loop

In the example below, the redo statement is used to skip the for loop when the value of variable i lies between 5 and 9.

#using redo inside for loop
for($i = 0; $i <= 10; $i++){
  if($i >= 5 && $i <= 9) {
    $i++;

    #using redo statement
    redo;
  }
  print("i = $i \n");
}

The output of the above code will be:

i = 0 
i = 1 
i = 2 
i = 3 
i = 4 
i = 10