Main Content

Perl - redo and last without a loop

Archive - Originally posted on "The Horse's Mouth" - 2004-12-02 08:11:43 - Graham Ellis

Perl has next, last and redo commands which (by default) cause you to move on to the next iteration / exit from / repeat the same iteration of a loop.

Did you know that you can also label a block and then use them in a similar way in that block?


$c = 1;
$d = 4;
thyme:
{
$c++;
$e = 5;
redo thyme if ($c < 3);
$f = 6;
last thyme if ($e > 3);
$g = 7;
}
$h = 8;
print ("$c $d $e $f $g $h\n");


Result:


[localhost:~/dplp] graham% perl blocker
3 4 5 6 8
[localhost:~/dplp] graham%


Note - the "redo" lets you write a loop without there being any loop word used - dangerous unless you know what you're doing and almost as frowned upon as using a goto statement (of which Perl has three flavours!). See intermediate and advanced examples.