A.19 Modules and Packages

Chapter 1 summarizes the basic concepts of namespaces, packages, and modules.

A namespace is a table containing the names and values of variables and subroutines. Namespaces are excellent ways to protect one part of your code from unintentionally using the same variable or subroutine name as appears in another part of your code, causing a namespace collision and often leading to incorrect (but hard to identify) program behavior.

By default, a Perl program uses the namespace called main.

The package declaration enables you to declare and use different namespaces for different parts of your program. For instance, to declare a new namespace called Outer, use the following statement:

package Outer;

Package declarations usually occur at or near the top of a file and are in effect throughout the file, but they can appear several times within a file, causing the active namespace to switch each time they are called.

When a file has one package declaration at the top of the file and it's named with the package name followed by the .pm suffix (e.g, Outer.pm), the file is called a Perl module. (The module also needs to end with the statement "1;" to load correctly when called.)

The code for a Perl module can be used in a Perl program by referencing the file defining the module with a use statement, as in the following example:

use Outer;

The Perl interpreter will then try to find a file called Outer.pm.

Chapter 1 gives the basic details on how to manage modules so that the Perl interpreter can find them.