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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.