A Perl random integer example

Perl random integer FAQ: Can you provide a Perl random integer example?

In my earlier Perl random tutorial, I described several different ways of generating random numbers in Perl. Today I'd like to share a Perl script I wrote that uses a random integer number to rotate files on this website.

A Perl random integer script example

The following Perl script performs the following functions:

  • Determines how many files are in a given directory.
  • Gets a random integer that is one less than the number of files.
  • Copies the file in the Perl array that corresponds to the random number that was generated.

That description isn't great, so let me give you an example:

  • This Perl script runs, and find that there are 20 "*.txt" files in the directory.
  • The number 20 is assigned to the $num_files variable.
  • The variable $rand will hold a number that is anywhere between 0 and 19. For our example, let's say it is number 12.
  • The copy function below will get element number 12 from the @files array, and then copy the file given by that name to the filename ad-block.html.

I run this Perl random integer script from my Linux crontab file periodically. This script is currently responsible for rotating the Amazon and ThinkGeek ads shown on this website.

My Perl random integer file-rotation script

Without any further delay, here is the source code for my Perl random file rotation script:


# a perl random script.
# randomly rotate ad files.
# created by alvin alexander, devdaily.com

use strict;
use warnings;

use File::Copy;

my $ad_file = 'ad-block.html';

# get a list of all *.txt files in the current directory
opendir(DIR, ".");
my @files = grep(/\.txt$/,readdir(DIR));

# get the number of files in the directory
my $num_files = @files;

# get a random number that is less than the number of files
# in the current directory (note: 5 files results in a range of 0-4)
my $rand = int(rand($num_files));

# copy the random file to the actual ad file
copy($files[$rand], $ad_file);

Perl random integer - Discussion

As you can see, generating a random number in Perl is very simple. Just use the Perl rand function, wrap it in the Perl int function, and specify an upper limit. As you can see from this example, a simple Perl random integer function like this can also be extremely useful.