Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Answers to Chapter 10 Exercises

  1. Here’s one way to do it:

    my $secret = int(1 + rand 100);
    # This next line may be uncommented during debugging
    # print "Don't tell anyone, but the secret number is $secret.\n";
    
    while (1) {
      print "Please enter a guess from 1 to 100: ";
      chomp(my $guess = <STDIN>);
      if ($guess =~ /quit|exit|^\s*$/i) {
        print "Sorry you gave up. The number was $secret.\n";
        last;
      } elsif ($guess < $secret) {
        print "Too small. Try again!\n";
      } elsif ($guess == $secret) {
        print "That was it!\n";
        last;
      } else {
        print "Too large. Try again!\n";
      }
    }

    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 0 up to (but not including) 100. That is, the largest possible value of that expression is something like 99.999.[*] 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.

    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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page