1.8 Using Modules

So far, the benefit of modules may seem questionable. You may be wondering what the advantage is over simple libraries (without package declarations), since the main result seems to be the necessity to refer to subroutines in the modules with longer names!

1.8.1 Exporting Names

There's a way to avoid lengthy module names and still use the short ones if you place a call to the special Exporter module in the module code and modify the use MODULE declaration in the calling code.

Going back to the first example Geneticcode.pm module, recall it began with this line:

package Geneticcode;

and included the definition for the hash genetic_code and the subroutine codon2aa.

If you add these lines to the beginning of the file, you can export the symbol names of variables or subroutines in the module into the namespace of the calling program. You can then use the convenient short names for things (e.g., codon2aa instead of Geneticcode::codon2aa). Here's a short example of how it works (try typing perldoc Exporter to see the whole story):

package Geneticcode;

require Exporter;
@ISA = qw(Exporter);

@EXPORT_OK = qw(...);         # symbols to export on request

Here's how to export the name codon2aa from the module only when explicitly requested:

@EXPORT_OK = qw(codon2aa);    # symbols to export on request

The calling program then has to explicitly request the codon2aa symbol like so:

use Geneticcode qw(codon2aa);

If you use this approach, the calling program can just say:


instead of:


The Exporter module that's included in the standard Perl distribution has several other optional behaviors, but the way just shown is the safest and most useful. As you'll see, the object-oriented programming style of using modules doesn't use the Export facility, but it is a useful thing to have in your bag of tricks. For more information about exporting (such as why exporting is also known as "polluting your namespace"), see the Perl documentation for the Exporter module (by typing perldoc Exporter at a command line or by going to the http://www.perldoc.com web page).