DelphiFAQ Home Search:
General :: Programming :: perl
General questions about perl.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.
Recommended links on this topic:
Featured Article

Generating a random number

Question:

I need to generate a random number between 1 and 100. How do I do this with perl?

Answer:

You need two functions: srand() to initialize the random generator. This needs to be called only once at the beginning of your program. You may pass an argument to initialize srand, if you don't it will use a semi-random value based on the current time and process ID, among other things. If you think that you need really random random numbers e.g. for cryptography, then you should see the Math::TrulyRandom module in CPAN.

After initializing, use rand() each time you need a random number. rand() by default will return a value >= 0 and < 1.

Use rand(100) to get a value >=0 and < 100. Your code would look like this:

#!/usr/bin/perl

 srand(); # initialize

 my $num = rand(100) + 1;
 # 1 <= $num <= 100

 # picking a random array element
# this uses the $# operator to get the number 
# of elements in the array
my @options = ( 'red','yellow','green');
 print $options[int rand scalar @options];
 print $options[int rand $#options];

Generated 8:02:16 on Jan 23, 2018