Randomness In Perl

Perl’s rand() function is a little bit more interesting than PHP’s, because it’s behavior isn’t as finely tuned to the needs of website programmers, as PHP’s. Furthermore, perl’s rand() function is very flexible.

Rand Basics

The rand function returns a decimal number between 0, including 0, and the inputed number, not inclusive. Therefore, rand(7) would return a decimal between 0 and 7. If there is no input, then rand would return a number between 0 and 1.

But I Want A Number Between 0 And 50.

print int rand 51;

Perl’s rand() function isn’t built to give you integers. However, with the int() function you can make it do your bidding. However, it’s important to notice that you have to enter a number one greater than the largest number you’re looking for.

Rand And Arrays

my @array = ( ‘first possibility’,’second’,’third’);

print $array[int rand scalar @array];

This code works with almost any input as @array. URLs, images, possible passwords, whatever you need can be in @array. The function is returning the int rand result of the scalar value of @array. What’s important to note is that with arrays, the scalar value is one higher than the highest key value of @array (Perl’s arrays are indexed at 0).

Truly Random

Use of Perl’s rand() function is not advised for cryptographers. The rand() function uses a seed to generate its input, and unfortunately that seed is predictable approximately one third of the time. Check out perldoc -f srand and perldoc -f rand for more information on this. Instead, it’s advised that for truly random input, one should use the Perl Module Math::TrulyRandom.

Author: Gyan Kapur