Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Looking for a loop

by Anonymous Monk
on May 28, 2018 at 15:59 UTC ( [id://1215327]=note: print w/replies, xml ) Need Help??


in reply to Looking for a loop

Another way I often see it done (in any language):
$correct = false; // until otherwise do { ... prompt ... if (validation check) { $correct = true; // often 'last' here to end loop } say("You have chosen the wrong number") } until ($correct)

Replies are listed 'Best First'.
Re^2: Looking for a loop
by jeffenstein (Hermit) on May 28, 2018 at 16:31 UTC

    Translated to perl:

    #!/usr/bin/env perl use strict; use warnings; use utf8; use feature 'say'; sub choose { say "choose a number:"; say for 1..5; } my ($correct, $response); while(!$correct){ choose(); chomp($response = <>); if($response >= 1 && $response <= 5){ $correct = 1; } else{ say "You have chosen the wrong number"; } }

    But why not get rid of $correct, since you can just exit the loop?

    #!/usr/bin/env perl use strict; use warnings; use utf8; use feature 'say'; sub choose { say "choose a number:"; say for 1..5; } my $response; while(1){ choose(); chomp($response = <>); last if $response >= 1 && $response <= 5; say "You have chosen the wrong number"; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (None)
    As of 2024-04-25 02:05 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found