Perl: Generate Random Value

Using perl -e

$ perl -e 'print rand()'
0.421794341485114

Using debugger as REPL with perl -de x (x can be anything)

See: https://perldoc.perl.org/perlfaq3#How-can-I-use-Perl-interactively?

$ perl -de x
Loading DB routines from perl5db.pl version 1.53
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.

DB<1> print rand()
0.520274409166635

DB<2> print("between 0 and 1 => " . rand())
between 0 and 1 => 0.712479852896017

DB<3> print("0 or 1 => " . int(rand(2)))
0 or 1 => 1

DB<4> print("0 or 1 => " . int(rand(2)))
0 or 1 => 0

DB<5> $random_exit_code = int(rand(2))

DB<6> print("0 or 1 => ${random_exit_code}")
0 or 1 => 1

$ perl -e 'sleep(1)'
or
$ perl -e 'sleep 1'

# Run some command after some sleep
$ perl -e 'sleep rand(10)'; echo "after waiting randomly for a few seconds"
$ perldoc -f rand

    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,

                int(rand(10))

            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 Math::TrulyRandom.

Also see

Leave a Comment

Your email address will not be published. Required fields are marked *