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:
use Your::Module qw(your_neat_subroutine);
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;