Initializing Perl's rand

Ian McCulloch ianmcc at
Tue Jun 25 19:53:20 EST 2002

On Tue, 25 Jun 2002 Doug.Palmer at wrote:

> > Does perl initialize to the same seed each run?
> > How can I make it get a different seed each run?
> From 'man perlfunc':
> "Sets the random number seed for the "rand" opera­tor.  If EXPR is omitted,
> uses a semi-random value supplied by the kernel (if it supports the
> /dev/urandom device) or based on the current time and process ID, among
> other things.  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."
> time() has only second resolution and MacPerl may not have decent access to
> a process ID. So there may not be much randomness going on. At the very
> least, hashing the value of time() -- perhaps with Crypt::SHA for good
> entropy -- would be a good idea.

As aaid elsewhere, if the rand() function is any good, then hashing time() 
will give no additional benefit.

If the program is only running one instance at a time, the standard method 
would be to save the seed somewhere on exit, so you can restart from the 
saved position in the pseudo-random sequence.  Or you could munge the 
saved seed with time(), or something like that.

> You might want to use Math::TrulyRandom or Math::RandomOrg modules to
> initialise the seed. Math::TrulyRandom depends on some pretty unixy C code,
> however. Math::RandomOrg doesn't, but does need an internet connection.


More information about the linux mailing list