O'Reilly logo

Sams Teach Yourself Perl in 21 Days, Second Edition by Rafe Colburn, Laura Lemay

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required