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

Use the following simple function. It selects a random integer between (and possibly including!) the two given integers, e.g., random_int_in(50,120)

   sub random_int_in ($$) {
     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);
   }

Back to perlfaq4