Using the Perl rand() function
Introduction
The rand()
function is used to generate random numbers. By default it generates a number between 0 and 1, however you can pass it a maximum and it will generate numbers between 0 and that number.
Example 1. Between 0 and 1
To generate a random decimal number between 0 and 1, use rand()
without any parameters.
This will give you a random number, like:
Example 2. A bigger range of numbers
Quite often you don’t want a number between 0 and 1, but you want a bigger range of numbers. If you pass rand()
a maximum, it will return a decimal number between 0 and that number. Our example below generates a random number between 0 and 100.
The program will produce something like:
Example 3. A random integer
To generate a random integer, convert the output from rand to an integer, as follows:
This program gives you an integer from 0 to 99 inclusive:
Example 4. With an offset
To generate a random number between, for example, 100 and 150, simply work out the range and add the minimum value to your random number.
This program gives you: