Help language development. Donate to The Perl Foundation

P5rand cpan:ELIZABETH last updated on 2018-05-21


Build Status


P5rand - Implement Perl 5's rand() built-ins


use P5rand;

say rand;    # a number between 0 and 1

say rand 42; # a number between 0 and 42


This module tries to mimic the behaviour of the rand built-in of Perl 5 as closely as possible.


rand EXPR
rand    Returns a random fractional number greater than or equal to 0 and
        less than the value of EXPR. (EXPR should be positive.) If EXPR is
        omitted, the value 1 is used. Currently EXPR with the value 0 is
        also special-cased as 1 (this was undocumented before Perl 5.8.0
        and is subject to change in future versions of Perl).
        Automatically calls "srand" unless "srand" has already been
        called. See also "srand".

        Apply "int()" to the value returned by "rand()" if you want random
        integers instead of random fractional numbers. For example,


        returns a random integer between 0 and 9, inclusive.

        (Note: If your rand function consistently returns numbers that are
        too large or too small, then your version of Perl was probably
        compiled with the wrong number of RANDBITS.)

        "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, and


The version of srand() that is provided by Perl 6 does not allow it to be called without a parameter. Rather than providing a possibly predictable default seed value (like it does in Perl 5), it was decided to not offer thisi capability in Perl 6. This seems like a good idea, so this module does not provide a replacement srand function.

Currently, some Perl 6 grammar checks are a bit too overzealous with regards to calling rand with a parameter:

say rand(42);   # Unsupported use of rand(N)

This overzealousness can be circumvented by prefixing the subroutine name with &:

say &rand(42);  # 24.948543810572648

until we have a way to curb this overzealousness.


Elizabeth Mattijsen

Source can be located at: . Comments and Pull Requests are welcome.


Copyright 2018 Elizabeth Mattijsen

Re-imagined from Perl 5 as part of the CPAN Butterfly Plan.

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.