Perl continue Statement



A continue BLOCK, is always executed just before the conditional is about to be evaluated again. A continue statement can be used with while and foreach loops. A continue statement can also be used alone along with a BLOCK of code in which case it will be assumed as a flow control statement rather than a function.

Syntax

The syntax for a continue statement with while loop is as follows −

while(condition) {
   statement(s);
} continue {
   statement(s);
}

The syntax for a continue statement with foreach loop is as follows −

foreach $a (@listA) {
   statement(s);
} continue {
   statement(s);
}

The syntax for a continue statement with a BLOCK of code is as follows −

continue {
   statement(s);
}

Example

The following program simulates a for loop using a while loop −

#/usr/local/bin/perl
   
$a = 0;
while($a < 3) {
   print "Value of a = $a\n";
} continue {
   $a = $a + 1;
}

This would produce the following result −

Value of a = 0
Value of a = 1
Value of a = 2

The following program shows the usage of continue statement with foreach loop −

#/usr/local/bin/perl
   
@list = (1, 2, 3, 4, 5);
foreach $a (@list) {
   print "Value of a = $a\n";
} continue {
   last if $a == 4;
}

This would produce the following result −

Value of a = 1
Value of a = 2
Value of a = 3
Value of a = 4
perl_loops.htm
Advertisements