rand
rand EXPR
randThis function returns a pseudorandom floating-point number
greater than or equal to 0 and less than the value of
EXPR. (EXPR should
be positive.) If EXPR is omitted, the
function returns a floating-point number between 0 and 1 (including 0,
but excluding 1). rand automatically
calls srand unless srand has already been called. See also
srand.
To get an integral value, such as for a die roll, combine this
with int, as in:
$roll = int(rand 6) + 1; # $roll now a number between 1 and 6
Because Perl uses your own C library’s pseudorandom number
function, like random(3) or
drand48(3), the quality of the distribution is not
guaranteed. If you need stronger randomness, such as for cryptographic
purposes, you might consult instead the documentation on
random(4) if your system has a /dev/random or /dev/urandom device; the CPAN modules
Math::Random::Secure, Math::Random::MT::Perl, and Math::TrulyRandom; or a good textbook on computational generation of
pseudorandom numbers, such as the second volume of Knuth.[247]
[247] Knuth, D.E. The Art of Computer Programming, Seminumerical Algorithms, vol. 2, 3rd ed. (Reading, Mass.: Addison–Wesley, 1997).
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access