Chapter 11. Modules

The module is the fundamental unit of code reuse in Perl. Under the hood, it's just a package defined in a file of the same name (with .pm on the end). In this chapter, we'll explore how you can use other people's modules and create your own.

Perl comes bundled with a large number of modules, which you can find in the lib directory of your Perl distribution. Many of those modules are described in Chapter 32, and Glossary. All the standard modules also have extensive online documentation, which (horrors) may be more up-to-date than this book. Try the perldoc command if your man command doesn't work.

The Comprehensive Perl Archive Network (CPAN) contains a worldwide repository of modules contributed by the Perl community, and is discussed in Chapter 22. See also http://www.cpan.org.

Using Modules

Modules come in two flavors: traditional and object-oriented. Traditional modules define subroutines and variables for the caller to import and use. Object-oriented modules function as class definitions and are accessed through method calls, described in Chapter 12. Some modules do both.

Perl modules are typically included in your program by saying:

use MODULE LIST;

or just:

use MODULE;

MODULE must be an identifier naming the module's package and file. (The syntax descriptions here are meant to be suggestive; the full syntax of the use statement is given in Chapter 29.)

The use statement does a preload of MODULE at compile time and then an import of the symbols you've ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.