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

Viewed 143

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.

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

Related