Skip to content

Perl: Generating a Random Number with Rand()

Generating a psuedo random number is common programming task. This tutorial will show you how to this in Perl using the rand() function.

The Rand() Function

The simplest use of rand(), with no parameters ( This is analogous to calling rand(1) ), generates a double precision number between 0 and 1.

#!/usr/bin/perl
use strict
use warnings;

my $rndnum = rand()
print $rndnum;

Will give you a result like: 0.186135607379587

Rand() with a Range

You can generate a bigger random number if you call rand($int) where $int is the maximum value you want. For example, to generate a number between 0 and 10 we could use:

#!/usr/bin/perl
use strict
use warnings;

my $rndnum = rand(10)
print $rndnum;

This will give a result like: 5.9358180787331.

Alternatively, we could call rand() and multiply by the maximum value:

#!/usr/bin/perl
use warnings
use strict;

my $rndnum = rand() * 10
print $rndnum;

Which returns the result: 1.65611195917339.

Generating a Random Integer

If we want to generate a random integer, to use an array index for example, then we need to use another function to round our double. We have 3 choices: int(), ceil() and floor(). int() will return the integer part of an expression, ceil() will round up to the next integer and floor() will round down.

#!/usr/bin/perl
use strict
use warnings;

my $rndnum = rand(10)
print "$rndnum => ". int($rndnum);

Gives us: 4.03471924205409 => 4

Ceil and Round require the POSIX module:

#!/usr/bin/perl
use strict
use warnings;
use POSIX;

my $rndnum = rand(10)
print "$rndnum => ". ceil($rndnum);

Gives us: 4.03471924205409 =>5