Answer to Chapter 10 Exercise

A.9 Answer to Chapter 10 Exercise

1.       Here's one way to do it:

2.          my $secret = int(1 + rand 100);
3.          # This next line may be un-commented during debugging
4.          # print "Don't tell anyone, but the secret number is $secret.\n";
5.           
6.          while (1) {
7.           print "Please enter a guess from 1 to 100: ";
8.          chomp(my $guess = <STDIN>);
9.           if ($guess =~ /quit|exit|^\s*$/i) {
10.      print "Sorry you gave up. The number was $secret.\n";
11.     last;
12.      } elsif ($guess < $secret) {
13.      print "Too small. Try again!\n";
14.     } elsif ($guess == $secret) {
15.      print "That was it!\n";
16.     last;
17.      } else {
18.      print "Too large. Try again!\n";
19.     }
}

The first line picks out our secret number from 1 to 100. Here's how it works. First, rand is Perl's random number function, so rand 100 gives us a random number in the range from zero up to (but not including) 100. That is, the largest possible value of that expression is something like 99.999.[A] Adding one gives a number from 1 to 100.999, then the int function truncates that, giving a result from 1 to 100, as we needed.

[A] The actual largest possible value depends upon your system; see http://www.cpan.org/doc/FMTEYEWTK/random if you really need to know.

The commented-out line can be helpful during development and debugging, or if you like to cheat. The main body of this program is the infinite while loop. That will keep asking for guesses until we execute last.

It's important that we test the possible strings before the numbers. If we didn't, do you see what would happen when the user types quit? That would be interpreted as a number (probably giving a warning message, if warnings were turned on), and since the value as a number would be zero, the poor user would get the message that their guess was too small. We might never get to the string tests, in that case.

Another way to make the infinite loop here would be to use a naked block with redo. It's no more or less efficient; merely another way to write it. Generally, if you expect to mostly loop, it's good to write while, since that loops by default. If looping will be the exception, a naked block may be a better choice.

 



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2001
Pages: 205

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net