Sets the random number seed for the
If srand() is not called explicitly, it is called implicitly at the
first use of the
rand operator. However, this was not true of
versions of Perl before 5.004, so if your script will run under older
Perl versions, it should call
Most programs won't even call srand() at all, except those that need a cryptographically-strong starting point rather than the generally acceptable default, which is based on time of day, process ID, and memory allocation, or the /dev/urandom device if available. You may also want to call srand() after a fork() to avoid child processes sharing the same seed value as the parent (and consequently each other).
You can call srand($seed) with the same $seed to reproduce the same sequence from rand(), but this is usually reserved for generating predictable results for testing or debugging. Otherwise, don't call srand() more than once in your program.
Do not call srand() (i.e., without an argument) more than once per process. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling srand() again actually loses randomness.
Most implementations of
srand take an integer and will silently
truncate decimal numbers. This means
srand(42) will usually
produce the same results as
srand(42.1). To be safe, always pass
srand an integer.
In versions of Perl prior to 5.004 the default seed was just the
time. This isn't a particularly good seed, so many old
programs supply their own seed value (often
time ^ $$
($$ + ($$ << 15))
), but that isn't necessary any more.
For cryptographic purposes, however, you need something much more random than the default seed. Checksumming the compressed output of one or more rapidly changing operating system status programs is the usual method. For example:
If you're particularly concerned with this, search the CPAN for random number generator modules instead of rolling out your own.
Frequently called programs (like CGI scripts) that simply use
- time ^ $$
for a seed can fall prey to the mathematical property that
- a^b == (a+1)^(b+1)
one-third of the time. So don't do that.