Function srand() in Perl

In the Perl programming language has a built-in function srand().

This function is used to set or get the number the sequence of numeric values from a function which returns rand().

Most often, the function of srand() used in the tests to each run the test function rand() return the same value.

Here is an example code:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;
use feature qw(say);

srand(16);

say int(rand(10));
say int(rand(10));
say int(rand(10));
say int(rand(10));
say int(rand(10));

The result of the program is always the same 5 numbers:

1
0
9
3
3

The program uses int(rand(10)) to get a random number between 0(inclusive) to 9(inclusive).

In the code there is a call srand(16);. This call sets the function rand() should return the number of pseudo-random sequence number 16. Therefore, each run of this program leads to the same result. If this program was not calling the function srand(), then different runs of the program may return different values.

Arguments

Function srand() can be used without any arguments or give her exactly one argument.

In the case if you pass more than one argument, it will error:

Too many arguments for srand at script.pl line 3, near "2)"
Execution of script.pl aborted due to compilation errors.

The function does not use variable $_. If there is a need to use it, then it must be explicitly passed to the function srand($_);.

The function expects a number as argument value. If the function receives is not a number she leads him to the number.

Function discards the fractional part and the sign. srand(-2.9) is the same as srand(2). Here is an example code that shows this:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;

foreach my $n (-2, 2, 2.1, 2.9, -2.1, -2.9) {
    my $real_n = srand($n);
    my @arr;
    foreach (1..5) {
        push @arr, int(rand(10));
    }
    printf "%4s  %s  (%s)\n", $n, $real_n, join(', ', @arr);
}

Return value

Starting with Perl 5.14 a function srand() always returns a number from 1 to 4294967296, or a string 0 but true. This number is the number sequence that is used in the function rand().

If the function srand() call with no arguments, it returns the number the sequence that was installed automatically.

If the function call with an argument it will return the value of the sequence number, that was installed from this argument:

▶ Run
#!/usr/bin/perl

use feature qw(say);

say srand(1573); # 1573
say srand(-2.9); # 2

It is interesting that for the sequence number 0 function returns a string 0 but true:

▶ Run
#!/usr/bin/perl

print srand(0);

Before Perl 5.14, the function srand() always returns the number 1.

Official documentation

Here is the output of the command perldoc -f srand:

    srand EXPR
    srand   Sets and returns the random number seed for the "rand" operator.

            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. 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 work *only* on Perls of a recent
            vintage:

                use 5.014;  # so srand returns the seed

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

            Do not call "srand()" (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
            calling "srand" again actually *loses* randomness.

            Most implementations of "srand" take an integer and will
            silently truncate decimal numbers. This means "srand(42)" will
            usually produce the same results as "srand(42.1)". To be safe,
            always pass "srand" 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, and Math::TrulyRandom.

Related topics

Other articles