Packaging your Code

Reusable code can be packaged into "modules" that can be included. Modules must have a strict format:

Minimalistic Example

 # Package file named Greet.pm
 # ---------------------------
 package Greet;
 use strict;

 sub greet {
    my $name = shift;
    print("Welcome, $name.\n");
 }
 sub bye {
    my $name = shift;
    print("Good-bye, $name, sorry to see you go.\n");
 }
 1;

Example of usage:

 use strict;
 use Greet;

 Greet::greet('my friend');
 Greet::bye('Fred');

Namespace Control

Normally a Perl module will "export" its names (subroutines, variables) into a namespace with the same name as the package. E.g., the above package Greet.pm has two subs (greet and bye) that will be exported into namespace Greet, and hence will be known as Greet::greet and Greet::bye.

In order to export into the "main" namespace, which is what you often want, use module Exporter. Run "perldoc Exporter" for the fine details:

 package Greet;
 use strict;
 use Exporter;

 our @ISA = qw(Exporter);
 our @EXPORT = qw(greet bye);

 sub greet {
    my $name = shift;
    print("Welcome, $name.\n");
 }
 sub bye {
    my $name = shift;
    print("Good-bye, $name, sorry to see you go.\n");
 }
 1;

Example usage:

 use strict;
 use Greet;

 # Greet.pm's symbols (greet and bye) are now available
 # in our own namespace:
 greet('my friend');
 bye('Fred');