Chapter 6. Modules

Life is a struggle with things to maintain itself among them. Concepts are the strategic plan we form in answer to the attack.

Jose Ortega y Gasset, The Revolt of the Masses

One of the chief reasons why languages such as awk and the various Unix shells don’t get used for building even moderately complex systems is their lack of support for modular programming. There are no bodies of code that you can just pick up and plug into your application; instead, you end up cutting and pasting from other standalone scripts. In contrast, languages such as Perl have been highly successful because of the wide availability of third-party modules (libraries). When comparing languages, I consider the availability of libraries to be more important than pure language features.

Perl allows you to partition your code into one or more reusable modules. In this chapter, we will study how to:

  • Define modules using the package keyword.

  • Load predefined modules with use and require; we have already seen a few examples of use in the earlier chapters.

  • Access package specific variables and subroutines using the “::” notation.

  • Load functions at run-time.

Basic Package

The package keyword signifies the beginning of a new namespace. All global identifiers (names of variables, subroutines, filehandles, formats, and directory handles) mentioned after this statement “belong” to that package. For example:

            package BankAccount; $total = 0; sub deposit { my ($amount)= @_; $total += $amount; print "You ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.