Perl Part I · Module 12 · Modules and Packages
Exporting With Exporter
Chapter 12.5's module file had one line this track has not yet explained, and it encodes a policy rather than a mechanism. A module can hand its subroutine names straight into the caller's package so they can be called without a prefix, and it gets to choose between two rules for doing so: wait until a caller asks, or install them whether anyone asked or not. The names look almost identical — @EXPORT_OK and @EXPORT — and the difference between them is the difference between a library and a nuisance. Section one measures all four combinations in one table, and the row that matters is the one where a caller writes a bare use line, requests nothing at all, and finds two new subroutine names in their file. On a script that already has a subroutine by one of those names, that is a redefinition you did not ask for and were not warned about. The chapter closes on the refusal: Exporter will not hand over a subroutine that exists in the module but was not offered, and it refuses at compile time.
Intermediate12 min readPerlPart IModules
Part I · Module 12 · Chapter 12.6 · Exporting With Exporter
1. Two Policies, Measured Side by Side
Two modules offer the same two subroutines. The only difference is which array they list them in.
use strict;
use warnings;
use File::Temp qw(tempdir);
use File::Spec;
my $dir = tempdir(CLEANUP => 1);
mkdir File::Spec->catdir($dir, "Demo");
# Two modules offering the same two subs, by different policies.
my %mod = (
"Asked.pm" => <<'M',
package Demo::Asked;
use Exporter 'import';
our @EXPORT_OK = qw(wanted helper);
sub wanted { "wanted" }
sub helper { "helper" }
1;
M
"Default.pm" => <<'M',
package Demo::Default;
use Exporter 'import';
our @EXPORT = qw(wanted helper);
sub wanted { "wanted" }
sub helper { "helper" }
1;
M
);
for my $f (sort keys %mod) {
open my $fh, ">", File::Spec->catfile($dir, "Demo", $f) or die $!;
print $fh $mod{$f}; close $fh;
}
# Four child scripts, each probing one import style.
my @probe = (
[ 'EXPORT_OK, asked for one', qq{use Demo::Asked qw(wanted);\nprint defined(&wanted) ? "wanted: yes" : "wanted: no", " ";\nprint defined(&helper) ? "helper: yes" : "helper: no", "\\n";} ],
[ 'EXPORT_OK, asked for none', qq{use Demo::Asked;\nprint defined(&wanted) ? "wanted: yes" : "wanted: no", " ";\nprint defined(&helper) ? "helper: yes" : "helper: no", "\\n";} ],
[ 'EXPORT, asked for none', qq{use Demo::Default;\nprint defined(&wanted) ? "wanted: yes" : "wanted: no", " ";\nprint defined(&helper) ? "helper: yes" : "helper: no", "\\n";} ],
[ 'EXPORT, with ()', qq{use Demo::Default ();\nprint defined(&wanted) ? "wanted: yes" : "wanted: no", " ";\nprint defined(&helper) ? "helper: yes" : "helper: no", "\\n";} ],
);
for my $p (@probe) {
my ($label, $src) = @$p;
my $f = File::Spec->catfile($dir, "probe.pl");
open my $fh, ">", $f or die $!; print $fh "use strict;\nuse warnings;\nuse lib '$dir';\n$src"; close $fh;
my $out = `perl "$f" 2>&1`; $out =~ s/\s+\z//;
printf "%-26s %s\n", $label, $out;
}EXPORT_OK, asked for one wanted: yes helper: no
EXPORT_OK, asked for none wanted: no helper: no
EXPORT, asked for none wanted: yes helper: yes
EXPORT, with () wanted: no helper: noRead the four rows as a table. defined(&name) asks whether a subroutine of that name exists in the calling package, which is exactly the question "did the import install it".
Row 1 — @EXPORT_OK, asked for wanted. Got wanted, did not get helper. The caller received precisely what they requested.
Row 2 — @EXPORT_OK, asked for nothing. Got neither. The module is loaded and usable by fully-qualified name, and nothing was added to the caller's namespace. This is the behaviour Chapter 12.4's use VLSI::Log () produced, here arrived at by the module's policy rather than the caller's syntax.
Row 3 — @EXPORT, asked for nothing. Got both. The caller wrote use Demo::Default; with no import list whatsoever and two subroutine names appeared in their file.
Row 4 — @EXPORT, with explicit (). Got neither, so the caller can refuse — but only if they know that @EXPORT is in play and that empty parentheses are the way to opt out.
2. What the Module Writes
The mechanism is three lines, and two of them are in Chapter 12.5's file already.
use Exporter 'import'; borrows Exporter's import subroutine into your package. Chapter 12.3's equivalence explains why that is the relevant method: use Module LIST is BEGIN { require Module; Module->import(LIST); }, so whatever import does is what importing means.
our @EXPORT_OK = qw(parse_slack worst_slack); is the offer. These names may be requested.
our @EXPORT = qw(...) is the other policy, and the advice is to leave it empty — which is the default, so the advice is really "do not write this line".
You will also see the older form our @ISA = ('Exporter');, which makes your package inherit import rather than borrow it. It works identically for this purpose and appears in most code written before about 2005. use Exporter 'import'; is preferred now because it does not drag an inheritance relationship into a module that is not otherwise object-oriented — and Chapter 12.13 covers reading @ISA when you meet it.
For completeness, Exporter also supports tag sets: our %EXPORT_TAGS = (all => [@EXPORT_OK]); lets a caller write use Demo::Asked qw(:all). That is a grouping convenience rather than a new capability, and a module small enough to be readable rarely needs it.
3. Exporter Refuses What Was Not Offered
use strict;
use warnings;
use File::Temp qw(tempdir);
use File::Spec;
my $dir = tempdir(CLEANUP => 1);
mkdir File::Spec->catdir($dir, "Demo");
open my $fh, ">", File::Spec->catfile($dir, "Demo", "Strict.pm") or die $!;
print $fh "package Demo::Strict;\nuse Exporter 'import';\nour \@EXPORT_OK = qw(offered);\nsub offered { 1 }\nsub private { 1 }\n1;\n";
close $fh;
for my $name (qw(offered private nosuchthing)) {
my $f = File::Spec->catfile($dir, "probe.pl");
open my $p, ">", $f or die $!;
print $p "use lib '$dir';\nuse Demo::Strict qw($name);\nprint \"imported $name\\n\";\n";
close $p;
my $out = `perl "$f" 2>&1`;
my ($first) = split /\n/, $out;
$first =~ s/ at .* line \d+.*$//;
printf "asked for %-12s : %s\n", $name, $first;
}
print "\nExporter refuses a name the module did not offer -- at COMPILE time\n";asked for offered : imported offered
asked for private : "private" is not exported by the Demo::Strict module
asked for nosuchthing : "nosuchthing" is not exported by the Demo::Strict module
Exporter refuses a name the module did not offer -- at COMPILE timeThree requests, one granted.
The second row is the interesting one. private is a real subroutine in that module — it is defined right there next to offered — and the import is still refused, because it is not in @EXPORT_OK. So @EXPORT_OK is the offer, not the inventory. A subroutine the module does not list is still callable by its full name, Demo::Strict::private(), because Chapter 12.2 established that package subroutines are global names; what @EXPORT_OK controls is only whether the short name can be imported.
That distinction matters when designing a module. Leaving a helper out of @EXPORT_OK is a statement of intent — "this is not part of what I promise" — and it is enforced for imports and not for determined callers. If you need genuine privacy, the tool is a lexical subroutine or a closure over file-scoped my data, which is Chapter 12.11's subject.
The refusal happens at compile time, which follows from the same equivalence: import is called inside an implicit BEGIN. So a typo in an import list stops the program before it runs, exactly like a missing module. That is the good failure mode from Chapter 12.3, applied to names.
4. Deciding What To Offer
The mechanism is settled; the judgement is the chapter's real content, and it follows from Chapter 12.1's point that exported names become an interface.
Offer the two or three things callers need. VLSI::Log offers parse_slack and worst_slack because those are the operations a report script performs. A pattern it uses internally, a normalisation helper, a constant — none of those are the module's purpose and none should be in the list.
Leave @EXPORT empty. The exception is a module whose entire purpose is to provide one ubiquitous name, where every caller wants it and the name is unmistakable. Core modules do this sparingly, and your project module almost certainly is not one of them.
Export subroutines, not variables. Exporter can export $scalars and @arrays, and doing so publishes mutable state under a short name in someone else's file, which is harder to trace than a package variable. Chapter 12.7 measures what our already exposes.
Prefer a longer name over a popular one. parse_slack is safe; parse is not, and log would collide with the built-in. A module that exports log will produce errors in the caller that look nothing like an export problem.
Let the caller's use line be documentation. With @EXPORT_OK, use VLSI::Log qw(parse_slack worst_slack); states exactly which parts of the module this file depends on. That is information a reader wants and a bare use VLSI::Log; destroys.
5. What To Remember
@EXPORT_OKis what a caller may ask for;@EXPORTis installed whether they asked or not. Measured: a bareuseof the@EXPORTmodule put both names in the caller's package.- Use
@EXPORT_OK. The caller listing what they want is a benefit, not a cost — theuseline becomes a dependency record. - A caller can opt out of
@EXPORTwith(), but has to know to. @EXPORTcan silently redefine a caller's own subroutine, producing aredefinedwarning on a line that names neither.- The mechanism is
use Exporter 'import';plus the array. The olderour @ISA = ('Exporter');is equivalent and common in pre-2005 code. - Exporter refuses a name that was not offered, at compile time — even one that exists in the module.
@EXPORT_OKis the offer, not the inventory. - An unexported subroutine is still callable by its full name. For real privacy you need a closure over file-scoped
mydata (Chapter 12.11). - Export subroutines rather than variables, and prefer a specific name over a popular one.
Chapter 12.7 turns to the other half of what a module file declares: the difference between our, which makes a variable part of the package and reachable from anywhere, and my, which makes it private to the file — and why a module's own settings usually want neither of them.
Where this fits
Part of the Perl curriculum.
