An Example: Pick a Number

In this example, we'll play a sort of game where Perl prompts you for a number, picks a random number between 1 and your number, and then has you try to guess which number it's picked, like this:

% picknum.pl
Enter top number: 50
Pick a number between 1 and 50: 25
Too high!
Pick a number between 1 and 50: 10
Too low!
Pick a number between 1 and 50: 17
Too high!
Pick a number between 1 and 50: 13
Too high!
Pick a number between 1 and 50: 12
Correct!
Congratulations!  It took you 5 guesses to pick the right number.
%

This script makes use of two while loops and a number of if tests, as well as the rand function to pick the number. Listing 6.1 shows the code, our longest script so far.

Listing 6.1. The picknum.pl Script ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.