dennismv dennismv - 6 months ago 8
Perl Question

Why does "last" behave differently in Perl in these examples?

This loop never stops:

while (1)
{
while (1)
{
last;
}
}


This loop stops

while (1)
{
do
{
last;
}
while (1);
}


Without
last
, they are similar in their infinity. The 2nd loop structure does not appear to consider the inner loop as a loop. I presume in 2nd structure
last
actually exits the outer loop, before the inner loop begins. But why? Does the inner loop actually starts "later", after
do{}
has completed its first execution?

Answer

From perldoc -f last:

last cannot be used to exit a block that returns a value such as eval {} , sub {} , or do {} , and should not be used to exit a grep() or map() operation.

do {
   # ... 
} while (1); 

is not actually a looping in Perl, so last, next, redo don't function properly inside of it.

A single block is in fact a loop though, so you can wrap your do expression in a block to allows last to function as you expect:

{
   do {
      last; 
   } while (1); 
}

A more intuitive solution would by to have a sentinel value that controls exectution:

my $should_stop = 0;
do {  
   if ( <some-condition> ) { $should_stop = 1; }
} while ( !$should_stop ) 
Comments