Movatterモバイル変換


[0]ホーム

URL:


functions /srand
(source,CPAN)
You are viewing the version of this documentation from Perl 5.18.4.View the latest version
#srand EXPR
#srand

Sets and returns the random number seed for therand operator.

The point of the function is to "seed" therand function so thatrand can produce a different sequence each time you run your program. When called with a parameter,srand uses that for the seed; otherwise it (semi-)randomly chooses a seed. In either case, starting with Perl 5.14, it returns the seed. To signal that your code will workonly on Perls of a recent vintage:

use 5.014;# so srand returns the seed

Ifsrand() is not called explicitly, it is called implicitly without a parameter at the first use of therand operator. However, there are a few situations where programs are likely to want to callsrand. One is for generating predictable results, generally for testing or debugging. There, you usesrand($seed), with the same$seed each time. Another case is that you may want to callsrand() after afork() to avoid child processes sharing the same seed value as the parent (and consequently each other).

Donot callsrand() (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 callingsrand() again actuallyloses randomness.

Most implementations ofsrand take an integer and will silently truncate decimal numbers. This meanssrand(42) will usually produce the same results assrand(42.1). To be safe, always passsrand an integer.

A typical use of the returned seed is for a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed used for that run so that it can later be used to reproduce the same results.

rand() is not cryptographically secure. You should not rely on it in security-sensitive situations. As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including:Data::Entropy,Crypt::Random,Math::Random::Secure, andMath::TrulyRandom.

Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.


[8]ページ先頭

©2009-2025 Movatter.jp