What are Perl Modules?


A Perl module is a reusable package defined in a library file whose name is the same as the name of the package with a .pm as extension.

A Perl module file called Foo.pm might contain statements like this.

#!/usr/bin/perl
package Foo;
sub bar {
   print "Hello $_[0]\n"
}
sub blat {
   print "World $_[0]\n"
}
1;

Few important points about Perl modules

  • The functions require and use will load a module.
  • Both use the list of search paths in @INC to find the module.
  • Both functions require and use call the eval function to process the code.
  • The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail).

The Require Function

A module can be loaded by calling the require function as follows −

#!/usr/bin/perl
require Foo;
Foo::bar( "a" );
Foo::blat( "b" );

You must have noticed that the subroutine names must be fully qualified to call them. It would be nice to enable the subroutine bar and blat to be imported into our own namespace so we wouldn't have to use the Foo:: qualifier.

The Use Function

A module can be loaded by calling the use function.

#!/usr/bin/perl
use Foo;
bar( "a" );
blat( "b" );

Notice that we didn't have to fully qualify the package's function names. The use function will export a list of symbols from a module given a few added statements inside a module.

require Exporter;
@ISA = qw(Exporter);

Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the list variable named @EXPORT: For Example −

package Module;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(bar blat);
sub bar { print "Hello $_[0]\n" }
sub blat { print "World $_[0]\n" }
sub splat { print "Not $_[0]\n" } # Not exported!
1;

Installing Perl Module

Download a Perl module in the form tar.gz file. Use the following sequence to install any Perl Module Person.pm which has been downloaded in as Person.tar.gz file.

tar xvfz Person.tar.gz
cd Person
perl Makefile.PL
make
make install

The Perl interpreter has a list of directories in which it searches for modules (global array @INC).

Updated on: 02-Dec-2019

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements