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"; }