Blame


1 ffd9a51f 2023-08-04 jrmu #!/usr/bin/perl
2 ffd9a51f 2023-08-04 jrmu
3 ffd9a51f 2023-08-04 jrmu # Make a program that will repeatedly ask the user to guess a
4 ffd9a51f 2023-08-04 jrmu # secret number from 1 to 100 until the user guesses the secret
5 ffd9a51f 2023-08-04 jrmu # number. Your program should pick the number at random by using
6 ffd9a51f 2023-08-04 jrmu # the magical formula int(1 + rand 100). See what the perlfun
7 ffd9a51f 2023-08-04 jrmu # documentation says about int and rand if you're curious about
8 ffd9a51f 2023-08-04 jrmu # these functions. When the user guesses wrong, the program should
9 ffd9a51f 2023-08-04 jrmu # respond, "Too high", or "Too low." If the user enters the word
10 ffd9a51f 2023-08-04 jrmu # quit or exit, or if the user enters a blank line, the program
11 ffd9a51f 2023-08-04 jrmu # should quit. Of course, if the user guesses correctly, the
12 ffd9a51f 2023-08-04 jrmu # program should quit then as well!
13 ffd9a51f 2023-08-04 jrmu
14 ffd9a51f 2023-08-04 jrmu use warnings;
15 ffd9a51f 2023-08-04 jrmu use strict;
16 ffd9a51f 2023-08-04 jrmu use utf8;
17 ffd9a51f 2023-08-04 jrmu
18 ffd9a51f 2023-08-04 jrmu my $secret = int(1 + rand 100);
19 ffd9a51f 2023-08-04 jrmu my $guess;
20 ffd9a51f 2023-08-04 jrmu print "Guess (1-100): ";
21 ffd9a51f 2023-08-04 jrmu while (chomp($guess = <>) && $guess !~ /(exit|quit)|\A\z/) {
22 ffd9a51f 2023-08-04 jrmu if ($guess == $secret) {
23 ffd9a51f 2023-08-04 jrmu print "Correct!\n";
24 ffd9a51f 2023-08-04 jrmu last;
25 ffd9a51f 2023-08-04 jrmu } elsif (defined($guess) && $guess < $secret) {
26 ffd9a51f 2023-08-04 jrmu print "Too low!\n";
27 ffd9a51f 2023-08-04 jrmu } elsif (defined($guess) && $guess > $secret) {
28 ffd9a51f 2023-08-04 jrmu print "Too high!\n";
29 ffd9a51f 2023-08-04 jrmu }
30 ffd9a51f 2023-08-04 jrmu print "Guess (1-100): ";
31 ffd9a51f 2023-08-04 jrmu }
32 ffd9a51f 2023-08-04 jrmu print "Exiting!\n";