Gary Yang wrote:
> Hi,
>
> I need to get a random number whenever the perl script is called. Each
> time the random number I got should be different. I use that number to
> name generated files, i.e. I want the perl script to generate different
> file names whenever it is called. Can someone tell me how to get the
> different random number whenever the perl script is called?
Did you read perlfunc man page under rand and srand ?
Did you look in the FAQs ?
perlfaq4:
How do I get a random number between X and Y?
"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);
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_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);
}
----------------------
You could also try something like:
srand (time ^ $$);
to seed the generator before using rand to hopefully make it a little more
random.
_______________________________________________
Perl-Unix-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs