Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^3: How many loops are there in Perl?

by adamcrussell (Hermit)
on Jan 31, 2012 at 22:14 UTC ( #951085=note: print w/ replies, xml ) Need Help??


in reply to Re^2: How many loops are there in Perl?
in thread How many loops are there in Perl?

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)


Comment on Re^3: How many loops are there in Perl?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://951085]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2014-08-31 01:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls