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

Get Perl Cookbook 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.