perlfunc
gods
<P>
srand - seed the random number generator
<P>
<HR>
<P>
srand
<FONT SIZE=-1>EXPR</FONT>
<P>
srand
<P>
<HR>
<P>
Sets the random number seed for the [perlfunc:rand|rand()] operator. If
<FONT SIZE=-1>EXPR</FONT> is omitted, uses a semi-random value based on the current time and process
<FONT SIZE=-1>ID,</FONT> among other things. In versions of Perl prior to 5.004 the default seed was just the current
[perlfunc:time|time()]. This isn't a particularly good seed, so many old programs supply their
own seed value (often [perlfunc:time|time ^ $$] or
[perlfunc:time|time ^ ($$ + ($$ << 15))]), but that isn't necessary any more.
<P>
In fact, it's usually not necessary to call [perlfunc:srand|srand()] at all, because if it is not called explicitly, it is called implicitly at
the first use of the [perlfunc:rand|rand()] operator. However, this was not the case in version of Perl before 5.004,
so if your script will run under older Perl versions, it should call [perlfunc:srand|srand()].
<P>
Note that you need something much more random than the default seed for
cryptographic purposes. Checksumming the compressed output of one or more
rapidly changing operating system status programs is the usual method. For
example:
<P>
<PRE> srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);
</PRE>
<P>
If you're particularly concerned with this, see the <CODE>Math::TrulyRandom</CODE>
module in
<FONT SIZE=-1>CPAN.</FONT>
<P>
Do <EM>not</EM> call [perlfunc:srand|srand()] multiple times in your program unless you know exactly what you're doing
and why you're doing it. The point of the function is to ``seed'' the [perlfunc:rand|rand()] function so that [perlfunc:rand|rand()] can produce a different sequence each time you run your program. Just do it
once at the top of your program, or you <EM>won't</EM> get random numbers out of [perlfunc:rand|rand()]!
<P>
Frequently called programs (like
<FONT SIZE=-1>CGI</FONT> scripts) that simply use
<P>
<PRE> time ^ $$
</PRE>
<P>
for a seed can fall prey to the mathematical property that
<P>
<PRE> a^b == (a+1)^(b+1)
</PRE>
<P>
one-third of the time. So don't do that.
<HR>