Modules

  • A set of related functions and variables in a library file
  • A package with the same name as the file
  • Perl module files have the extension .pm
  • Module names are capitalized (i.e. MyModule.pm)
  • Some::Module corresponds to Some/Module.pm
  • @EXPORT  : Symbols (functions and variables) that will be exported by default
  • @EXPORT_OK  : Symbols that can optionally be exported
  • The ampersand in front of a function is optional (and the code is more efficient without it)

Using a module

  • Import all symbols that are exported by default:
use Some::Module;
  • Import only the specified symbols:
use Some::Module qw($var1 func1);
  • Import none of the symbols:
use Some::Module ();

Sample module

package MyModule;   # MyModule.pm

use strict;
use warnings;

BEGIN {
use Exporter (); # Do not import any symbols from Exporter
our (@ISA, @EXPORT, @EXPORT_OK);

@ISA = qw(Exporter);

# Symbols that are exported by default
@EXPORT = qw($var1 func1);

# Symbols that are optionally exported
@EXPORT_OK = qw($var2 func2);
}
our @EXPORT_OK;


# Declare package variables
our ($var1, $var2, $var3);

# Initialize package variables
$var1 = "This is var1\n";
$var2 = "This is var2\n";
$var3 = "This is var3\n";

# Define functions
sub func1 { print "This is func1\n"; }
sub func2 { print "This is func2\n"; }
sub func3 { print "This is func3\n"; }


# Module clean-up code
END {
}

# Main execution of the module starts here
# ...

1; # Return a true value from the file
Using the sample module
# Import all symbols that are exported by default
use MyModule;

print $var1;
print $MyModule::var2;
print $MyModule::var3;

&func1();
&MyModule::func2();
&MyModule::func3();
# Import only the specified symbols
use MyModule qw($var1 $var2 func1 func2);

print $var1;
print $var2;
print $MyModule::var3;

&func1();
&func2();
&MyModule::func3();
# Import none of the symbols
use MyModule ();

print $MyModule::var1;
print $MyModule::var2;
print $MyModule::var3;

&MyModule::func1();
&MyModule::func2();
&MyModule::func3();