Book HomePerl CookbookSearch this book

2.8. Generating Different Random Numbers

Problem

Every time you run your program you get the same set of "random" numbers. You want Perl to produce different random numbers each time. This is important in nearly every application of random numbers, especially games.

Solution

Use Perl's srand function:

srand EXPR;

Discussion

Making random numbers is hard. The best that computers can do, without special hardware, is generate "pseudo-random" numbers, which are evenly distributed in their range of values. These are generated using a mathematical formula, which means that given the same seed (starting point), two programs will produce identical pseudo-random numbers.

The srand function creates a new seed for the pseudo-random number generator. If given an argument, it uses that number as the seed. If no argument is given, srand uses a value that's reasonably difficult to guess as the seed (as of Perl 5.004 or later; before that it just used time, which isn't random at all). Don't call srand more than once in a program.

If you haven't called srand yourself, Perl version 5.004 and later calls srand with a "good" seed the first time you call rand. Earlier versions did not, so the same program always produced the same sequence. If you prefer that behavior, call srand yourself with a particular seed:

srand( <STDIN> );

Just because Perl tries to use a good default seed does not necessarily guarantee that the numbers generated are cryptographically secure against the most intrepid crackers. Textbooks on cryptography are usually good sources of cryptographically secure random number generators.

See Also

The srand function in perlfunc (1); Chapter 3 of Programming Perl; Recipes Recipe 2.7 and Recipe 2.9; Bruce Schneier's excellent Applied Cryptography ; John Wiley & Sons (1995)


Previous: 2.7. Generating Random NumbersPerl CookbookNext: 2.9. Making Numbers Even More Random
2.7. Generating Random NumbersBook Index2.9. Making Numbers Even More Random

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.