Loading 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;This is equivalent to:
BEGIN {
require MODULE;
MODULE–>import();
}This happens during the compile phase, so any code in the module
runs during the compile phase. This usually isn’t a problem since most
code in modules lives in subroutines or methods. Some modules may load
additional modules, XS code, and other code components. Since Perl handles
a use when it runs into it, any
modifications to @INC need to happen
before the use. You probably want the
lib pragma (see Chapter 29), which you also
load with use.
If you want to load the module during the run phase, perhaps
delaying its inclusion until you run a subroutine that needs it, you can
use require:
require MODULE;MODULE must be a package name that
translates to the module’s file. The use translates :: to / and
then appends a .pm to the end. It
looks for that name in @INC. If your
module is named Animal::Mammal::HoneyBadger, this will look for
Animal/Mammal/HoneyBadger.pm. Once
loaded, the path where Perl found the file shows up in %INC. Perl loads a file once. Before it tries to
load a file, it looks in %INC to see whether it is already loaded. If so, it can ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access