Modules

Learn about the modules in Perl.

We'll cover the following...

Overview

We’ve seen functions, classes, and data structures used to organize code. Perl’s next mechanism for organization and extension is the module. A module is a package contained in its file and loadable with use or require. A module must be valid Perl code. It must end with an expression that evaluates to a true value so that the Perl parser knows it has loaded and compiled the module successfully.

There are no other requirements—only strong conventions.

Loading a Perl module

When we load a module, Perl splits the package name on double colons (::) and turns the components of the package name into a file path. This means that use StrangeMonkey; causes Perl to search for a file named StrangeMonkey.pm in every directory in @INC in order until it finds one or exhausts the list.

Similarly, use StrangeMonkey::Persistence; causes Perl to search for a file named Persistence.pm in every directory named StrangeMonkey/ present in every directory in @INC, and so on. use StrangeMonkey::UI::Mobile; causes Perl to search for a relative file path of StrangeMonkey/UI/Mobile.pm in every directory in @INC.

The resulting file may or may not contain a package declaration matching its filename—there’s no such technical requirement—but it’ll cause confusion without that match.

...