Perl random number FAQ: Can you show me some examples of how to get a random number in Perl?

## Perl random number - solution

In its simplest form, if you just need a random decimal number between 0 and 1.0, you can use the Perl rand function like this:

# generate a random number in perl with the rand function my $random_number = rand(); print $random_number, "\n";

When I save this Perl random number code to a file and run it three times, I get these results:

0.867944542159425 0.843199703916074 0.101251886998401

(Of course my numbers will vary the next time I run this code.)

## Perl random numbers - using a range (upper limit)

More than likely, when you want to create a random number in Perl, you'll really want to create a random number that is in a range, or at least create a random number that has an upper limit.

To create a random decimal number in Perl that is less than 100.0, you specify the upper limit in your Perl rand function call like this:

my $random_number = rand(100); print $random_number, "\n";

Again I ran this random number code three times, and got this output:

60.6877568950043 50.0123499966325 93.2344240210117

## Perl random numbers - generating a random integer (int)

Most of the time when I say I need a random number in Perl, what I really mean is that I need a random integer (int). To create a random integer in Perl that is less than a given number, wrap the Perl rand function call with a Perl "int" function call, like this:

my $random_number = int(rand(100)); print $random_number, "\n";

That code produces a random number between 0 and 99.

## A Perl random number range with a lower limit

If you want to make sure your random number also has a lower limit, you'll have to take care of this manually, but it's simple also.

For example, let's assume you need a random number that is greater than or equal to 20, but less than 50. This Perl random code will do the trick:

my $random_number = int(rand(30)) + 20; print $random_number, "\n";

The Perl rand function returns a number between 0 and 29, so by adding 20 to that result, we will get a number that is greater than or equal to 20 and less than or equal to 49.

Sorry, I'm too lazy today to test the following script, but I believe this is the correct general formula, as long as you understand that the lower number will be in the range returned, and the upper limit will not be in the range returned:

# generate a random number in perl in the range 20-49 $lower_limit = 20; $upper_limit = 50; my $random_number = int(rand($upper_limit-$lower_limit)) + $lower_limit; print $random_number, "\n";

## Perl random numbers - Summary

I hope these Perl random number examples have been helpful. We've seen how to generate a random decimal number, random integers, and random numbers in a range, including upper and lower range limits.

*help support my writing*

& keep this website running

& keep this website running