next up previous contents index
Next: CGI scripts Up: Subroutines, functions, and modules Previous: References to subroutines   Contents   Index


Modules

Having spent many hours perfecting your subroutine to do what you want it to do, and handle (mostly) all cases thrown at it, you'll probably want to start using it in a number of your scripts. The straightforward way to do this is to copy the code for your subroutine into each script where you want to use it, but the problem with this approach is if you later on want to change the subroutine, this would entail changing all occurrences of the sub in all scripts in which it appears. A more maintainable and scaleable approach is to use a module.

A module is a Perl file, conventionally ending with a .pm extension, which can contain definitions of subroutines (and variables) that you can import into a script. This import is done using use; for example, if at the top of your script you say

use File::Copy;
you then have available the copy function which allows you to copy a file from one location to another (see perldoc File::Copy for usage). Module names in Perl follow a certain convention: the double colons (::) indicate a directory separator, and Perl then looks, in this instance, for a file called File/Copy.pm, which will contain the code defining the copy function. Just like for searching for executables, though, Perl does not search all over your hard disc for the File.pm file - it looks only in those directories specified by a special variable called @INC (type perl -V at a command prompt, and look at the end of the output, for what @INC includes). The @INC array is defined by your system; you can add to it within your script by using
use lib qw(/path/to/my/perl/module/directory);

Here is an example of a simple module that exports a function silly:

# file Silly.pm
package Silly;
use strict;
use warnings;

our (@EXPORT_OK);
use base qw(Exporter);
@EXPORT_OK = qw(silly);

sub silly {
  print qq{Hello from the silly sub\n};
}

1;
Save this file as Silly.pm somewhere in your @INC directory. You can then use the module in your script as
use Silly qw(silly);
silly();
where the use Silly qw(silly); line instructs Perl that we wish to import the silly subroutine from the Silly module.

There are a few things to note about the contents of the module file:

Modules can also be used for exporting variables other than subroutines; here's an example of a module that exports the constant pi:

# file Silly.pm
package Silly;
use strict;
use warnings;

our (@EXPORT_OK);
use base qw(Exporter);
@EXPORT_OK = qw(silly PI);

use constant PI => 3.1415926539;

sub silly {
  print qq{Hello from the silly sub\n};
}

1;
which can be used in a script as
use Silly qw(PI);
print "Pi is ", PI;

next up previous contents index
Next: CGI scripts Up: Subroutines, functions, and modules Previous: References to subroutines   Contents   Index