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.
Some other articles
P206 - More Loops and Conditionals While, for, foreach or something else to loop. Ruby v Perl - a comparison example Perl - making best use of the flexibility, but also using good coding standards How a for loop works Java, Perl and other languages Some more advanced Perl examples from a recent course Multiway branches in Perl - the given and when syntax Alternative loops and conditionals in Ruby and Perl Are you learning Perl? Some more examples for you! A pint of Black Rat, and a lazy barman Setting a safety net or fallback value in Perl switch and case, or given and when in Perl For loop - checked once, or evety time? Ruby v Perl comparison and contrast Question Mark - Colon operator (Perl and PHP) Saying NOT in Perl, PHP, Python, Lua ... Ruby, C, Java and more - getting out of loops for loop - how it works (Perl, PHP, Java, C, etc) Smart English Output - via PHP and Perl ? : operator Breaking a loop - Ruby and other languages The ternary operator in Python What - no switch or case statement? This article