Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata