How to get a random number in Perl from N to M

Here is a task. In Perl, the program needs to obtain an integer random number between N and M. For example, you need to get a number from 1 to 6 as if throwing dice.

In order to do this you need to use the rand()function.

Here is sample code that displays a random number between 1 (inclusive) to 6 (also inclusive):

▶ Run
#!/usr/bin/perl

my $number = 1 + int(rand(6));

print $number;
  • rand(6) will return a fractional number from 0 (inclusive) to 6 (but not including the number 6).
  • int(rand(6)) will return an integer from 0 to 5
  • because we want to get the integer starting from 1 we need to add 1 to the result int(rand(6))

In general case, if we want to get an integer random number between $n to $m, then we need write:

▶ Run
#!/usr/bin/perl

my $n = 1;
my $m = 6;

my $number = $n + int(rand( $m - $n + 1 ));
print $number;

Related topics

Other articles