Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to using a continue block with a while loop in Perl?

Tags:

perl

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.

like image 496
Vicky Avatar asked Sep 28 '17 14:09

Vicky


People also ask

How do you continue a loop in Perl?

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.

What is while loop in Perl?

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.

What is the difference between for loop and for each loop in Perl?

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.

How do you stop a while loop in Perl?

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.


1 Answers

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

like image 161
mob Avatar answered Nov 15 '22 03:11

mob