From: PerlFAQ Server on 20 Feb 2010 12:00 This is an excerpt from the latest version perlfaq4.pod, which comes with the standard Perl distribution. These postings aim to reduce the number of repeated questions as well as allow the community to review and update the answers. The latest version of the complete 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 corrections. The perlfaq-workers also don't have access to every operating system or platform, so please include relevant details for corrections to examples that do not work on particular platforms. Working code is greatly appreciated. If you'd like to help maintain the perlfaq, see the details in perlfaq.pod.
|
Pages: 1 Prev: FAQ 2.15 Where can I buy a commercial version of perl? Next: One-Liner Mania |