FAQ 4.11 How do I get a random number between X and Y?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

4.11: How do I get a random number between X and Y?

To get a random number between two values, you can use the "rand()"
built-in to get a random number between 0 and 1. From there, you shift
that into the range that you want.

"rand(\$x)" returns a number such that "0 <= rand(\$x) < \$x". Thus what
you want to have perl figure out is a random number in the range from 0
to the difference between your *X* and *Y*.

That is, to get a number between 10 and 15, inclusive, you want a random
number between 0 and 5 that you can then add to 10.

my \$number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )

Hence you derive the following simple function to abstract that. It
selects a random integer between the two given integers (inclusive), For
example: "random_int_between(50,120)".

sub random_int_between {
my(\$min, \$max) = @_;
# Assumes that the two arguments are integers themselves!
return \$min if \$min == \$max;
(\$min, \$max) = (\$max, \$min)  if  \$min > \$max;
return \$min + int rand(1 + \$max - \$min);
}

--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any