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.
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
packagekeyword.Load predefined modules with
useandrequire; we have already seen a few examples ofusein 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 ...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