cwchen icon

[Perl 6] Guessing the number.

cwchen | PRO | 10/06/17 03:14:32 AM UTC | 0 ⭐ | 987 👁️ | Never ⏰ | []
Perl 6 |

0 B

|

None

|

0 👍

/

0 👎

constant $MIN = 1;
constant $MAX = 100;
 
# Get a random answer between $MIN and $MAX.
my $answer = ($MIN..$MAX).pick;
 
# Initial program state.
my $guess = -1;
my $upper = $MAX;
my $lower = $MIN;
 
loop {
    # Get the guess from user.
    loop {
        my $input = prompt("Guess a number between {$lower} and {$upper}: ");
        
        # Check input is a valid number.
        unless $input ~~ m/ \d+ / {
            $*ERR.say: "Invalid number";
            redo;
        }
 
        # Check 
        unless $lower <= $input and $input <= $upper {
            $*ERR.say: "Invalid range";
            redo;
        }
 
        # Update the guess.
        $guess = $input;
        last;
    }
 
    # Check whether the guess is right.
    if $guess == $answer {
        say "You got it";
        last;
    } elsif $guess > $answer {
        say "Too large";
        $upper = $guess;
    } else {
        say "Too small";
        $lower = $guess;
    }
}

Comments