icon Top 9 categories map      RocketAware > Perl >

srand EXPR

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    
srand EXPR
srand
Sets the random number seed for the rand operator. If EXPR is omitted, uses a semi-random value 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.

In fact, it's usually not necessary to call srand() at all, because if it is not called explicitly, it is called implicitly at the first use of the 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 srand().

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:

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

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

Do not call 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 rand() function so that rand() can produce a different sequence each time you run your program. Just do it once at the top of your program, or you won't get random numbers out of rand()!

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.

Source: Perl builtin functions
Copyright: Larry Wall, et al.
Next: stat FILEHANDLE

Previous: sqrt EXPR



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: Random Numbers




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfunc/srand.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments