7. Packages, Modules, and Objects
Over the years, Perl has evolved from a utilitarian scripting tool into a sophisticated object-oriented programming language. Many people continue to use Perl just for simple scripts, and Perl will continue to make simple tasks easy. However, Perl can also make difficult tasks possible, by writing reusable code and using object-oriented programming techniques. This chapter explains what Perl modules are and how to use them in your programs. Modules are written to accomplish tasks that either aren't implemented by Perl's built-in functions, or that could be done better. We say modules are "reusable" because anyone who needs to accomplish the same task can use that module instead of writing the code from scratch. As you write more and more Perl code, you'll undoubtedly find yourself using many of the modules other Perl programmers have provided. You may also find yourself writing modules and making them available for others to use.
The remainder of this book describes a significant portion of the
functionality that's present in publicly available Perl modules.
You'll find that a number of
standard
or
core
modules are
distributed with Perl; many of these modules are discussed in
Chapter 8,
Standard Modules
. Scores of other modules are available on CPAN, and virtually any
task you'd like to accomplish in Perl is implemented in a module found
there. For unbundled modules, you'll need to install the module on
your system, and then integrate it into your program with the
The Now your program can make use of the many functions and variables made available by the CGI module.use CGI; Packages (from which modules are built) are also the mechanism by which Perl's object-oriented features are implemented. But object-oriented programming isn't for everyone, and there's nothing in packages that forces the programmer to work with the object-oriented paradigm. 7.1 Namespaces and PackagesA namespace does what it says: it stores names (or identifiers), including names of variables, subroutines, filehandles, and formats. Each namespace has its own symbol table , which is basically a hash with a key for each identifier.
The default namespace for programs is In Perl, a namespace is held in a package . By convention, package names start with a capital letter, and you should follow that convention when you create your own packages.
Each package
starts with a
From inside one package, you can refer to variables from another
package by "qualifying" them with the package name. To do this, place
the name of the package followed by two colons (
If the package name is null, the
Packages may be nested inside other packages. However, the package name
must still be fully qualified. For example, if the package
The default Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|