Advertisement
cwchen

[Perl 6] Guessing the number.

Oct 5th, 2017
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 0.97 KB | None | 0 0
  1. constant $MIN = 1;
  2. constant $MAX = 100;
  3.  
  4. # Get a random answer between $MIN and $MAX.
  5. my $answer = ($MIN..$MAX).pick;
  6.  
  7. # Initial program state.
  8. my $guess = -1;
  9. my $upper = $MAX;
  10. my $lower = $MIN;
  11.  
  12. loop {
  13.     # Get the guess from user.
  14.     loop {
  15.         my $input = prompt("Guess a number between {$lower} and {$upper}: ");
  16.        
  17.         # Check input is a valid number.
  18.         unless $input ~~ m/ \d+ / {
  19.             $*ERR.say: "Invalid number";
  20.             redo;
  21.         }
  22.  
  23.         # Check
  24.         unless $lower <= $input and $input <= $upper {
  25.             $*ERR.say: "Invalid range";
  26.             redo;
  27.         }
  28.  
  29.         # Update the guess.
  30.         $guess = $input;
  31.         last;
  32.     }
  33.  
  34.     # Check whether the guess is right.
  35.     if $guess == $answer {
  36.         say "You got it";
  37.         last;
  38.     } elsif $guess > $answer {
  39.         say "Too large";
  40.         $upper = $guess;
  41.     } else {
  42.         say "Too small";
  43.         $lower = $guess;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement