SYNTAX 1:
while {
#some code
}
continue {
#some other code
}
SYNTAX 2:
while {
#some code
#some other code
}
Does SYNTAX 1 has any advantage over SYNTAX 2 ? assuming "some code"and "some other code" remain same set of lines in both the syntaxes. Or its just two different styles having no coding advantage.
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.
A while loop in Perl generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don't know the number of times we want the loop to be executed however we know the termination condition of the loop.
There is no difference. From perldoc perlsyn: The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.
In many programming languages you use the break operator to break out of a loop like this, but in Perl you use the last operator to break out of a loop, like this: last; While using the Perl last operator instead of the usual break operator seems a little unusual, it can make for some readable code, as we'll see next.
The continue
block executes when you call next
from the middle of the loop, so it provides a way to execute some common code between iterations, regardless of the path of execution through each iteration.
Compare
my $last_item;
for my $item (@list) {
if ($last_item eq $item) {
do_something();
$last_item = $item;
next;
}
if (condition2($item,$last_item)) {
$last_item = $item;
next;
}
do_something_else();
$last_item = $item;
}
with
my $last_item;
for my $item (@list) {
if ($last_item eq $item) {
do_something();
next;
}
if (condition2($item,$last_item)) {
next;
}
do_something_else();
} continue {
$last_item = $item;
}
Some examples of continue
in the wild:
HTTP::Cookies
PPIx::Regexp::Node
PDL::Core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With