PERL / CHAPTER 11
Packages and explicit public interfaces
AdvancedOrganize names without confusing packages with lexical scope.
By the end of this chapter
- Use qualified subroutine names
- Distinguish package symbols from lexical variables
- Keep import behavior intentional
The idea
A package supplies a namespace for named subroutines and package variables. It does not replace lexical scoping: my still creates lexical variables, while our declares access to a package variable under strict checking. Qualified names make the owning namespace visible, helping a reader distinguish unrelated helpers that happen to use the same short name.
A module usually places reusable code in a file that can be loaded and may export a deliberate set of names. Export only the operations that form the public interface rather than flooding a caller’s namespace. Loading, importing, and runtime invocation are different events; use performs its load and import during compilation. Keep initialization predictable and avoid depending on accidental caller globals.
use strict; use warnings;
{ package Metrics; sub double { my ($n)=@_; return $n*2; } }
print Metrics::double(6),"\n";12
The qualified call names the package owning double, avoiding any need to import an unqualified helper.
Try it yourself
Design a small module with two public helpers and private lexical configuration.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING