I have always thought redo was cool.
At first glance it doesn't look anything like a goto because it is usually used with bare blocks. The code below has redo going to the start of the nearest enclosing block.
{
print "Enter a number 0-9\n";
$number=<STDIN>;
chomp($number);
unless(length($number) == 1 && $number =~ /[0-9]/){
print "C'mon, man! give me a number 0-9!\n";
redo;
}
}
However, redo can take an argument (a block label) which makes it look much more goto-ish and less like elegant Perl. For example, we could redo (pun intended!) the example like this:
GET_NUMBER:{
print "Enter a number 0-9\n";
$number=<STDIN>;
chomp($number);
unless(length($number) == 1 && $number =~ /[0-9]/){
print "C'mon, man! give me a number 0-9!\n";
redo GET_NUMBER;
}
}
The biggest difference between redo and a pure goto is that redo must go to an enclosing block label whereas goto goes to any label.
This is still a valid redo:
my $number;
PROMPT_FOR_NUMBER:{
print "Enter a number 0-9\n";
GET_NUMBER:{
$number=<STDIN>;
chomp($number);
unless(length($number) ==1 && $number =~ /[0-9]/){
print "You don't want to give me one number ?\n";
redo PROMPT_FOR_NUMBER;
}
}
}
<jc> Why do people persist in asking me stupid questions?
<Petruchio> <insert mutually recursive response>
--an exchange from #perlmonks on irc.slashnet.org(2 March 2009 1345 EST)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.