Perl version

Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

srand

Perl 5 version 10.1 documentation
Recently read

srand

  • srand EXPR

  • srand

    Sets the random number seed for the rand operator.

    The point of the function is to "seed" the rand function so that rand can produce a different sequence each time you run your program.

    If srand() is not called explicitly, it is called implicitly at the first use of the rand operator. However, this was not the case in versions of Perl before 5.004, so if your script will run under older Perl versions, it should call srand.

    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 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 in a script. 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 current time. This isn't a particularly good seed, so many old programs supply their own seed value (often time ^ $$ or 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:

    1. srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);

    If you're particularly concerned with this, see the Math::TrulyRandom module in CPAN.

    Frequently called programs (like CGI scripts) that simply use

    1. time ^ $$

    for a seed can fall prey to the mathematical property that

    1. a^b == (a+1)^(b+1)

    one-third of the time. So don't do that.