Perl - Continue Statement
In Perl, a continue block of code is used with loop statements like while loop, until loop and foreach loop. A continue block of code is always executed just before the loop condition is about to be evaluated again.
A continue block of code can also be used without any loop statement in that case it is assumed as a flow control statement rather than a function.
Syntax
#continue statement with while loop while (condition) { statements; } continue { statements; } #continue statement with until loop until (condition) { statements; } continue { statements; } #continue statement with foreach loop foreach variable (list){ statements; } continue { statements; } #continue statement without loop statement continue { statements; }
Continue statement with While loop
In the example below, the continue statement is used with while loop and it updates the variable i in each iteration.
$i = 0; while ($i < 6){ print("i = $i \n"); } continue { $i++; }
The output of the above code will be:
i = 0 i = 1 i = 2 i = 3 i = 4 i = 5
Continue statement with Until loop
In the example below, the continue statement is used with until loop. It is used to get out of the loop when variable i becomes 5.
$i = 0; until ($i == 10){ print("i = $i \n"); $i++; } continue { if($i == 5){ last; } }
The output of the above code will be:
i = 0 i = 1 i = 2 i = 3 i = 4
Continue statement with Foreach loop
In this example, the continue statement is used with foreach loop and it is used to get out of the loop when element with value 40 is found.
@numbers = (10, 20, 30, 40, 50); foreach $i (@numbers) { print "i = $i\n"; } continue { last if $i == 40; }
The output of the above code will be:
i = 10 i = 20 i = 30 i = 40