O'Reilly logo

Learning Perl Objects, References, and Modules by Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12. Using Modules

A module is a building block for your program: a set of related subroutines and variables packaged so it can be reused. This chapter looks at the basics of modules: how to bring in modules that others have written, and how to write modules of your own.

Sample Function-Oriented Interface: File::Basename

To understand what happens with use, look at one of the many modules included with a normal Perl distribution: File::Basename. This module parses file specifications into useful pieces in a mostly portable manner. The default usage:

use File::Basename;

introduces three subroutines, fileparse, basename, and dirname,[60] into the current package: typically, main in the main part of your program. From this point forward, within this package, you can say: [61]

my $basename = basename($some_full_path);
my $dirname = dirname($some_full_path);

as if you had written the basename and dirname subroutines yourself, or (nearly) as if they were built-in Perl functions.[62]

However, suppose you already had a dirname subroutine? You’ve now overwritten it with the definition provided by File::Basename! If you had turned on warnings, you’d see a message stating that, but otherwise, Perl really doesn’t care.

Selecting What to Import

Fortunately, you can tell the use operation to limit its actions. Do this by specifying a list of subroutine names following the module name, called the import list:

use File::Basename ("fileparse", "basename");

Now define the two given ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required