This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl 5.003_01: lib/Cwd.pm
[perl5.git] / lib / Exporter.pm
CommitLineData
8990e307
LW
1package Exporter;
2
748a9306 3require 5.001;
8990e307 4
a0d0e21e 5$ExportLevel = 0;
c07a80fd 6$Verbose = 0 unless $Verbose;
748a9306
LW
7
8require Carp;
a0d0e21e
LW
9
10sub export {
748a9306
LW
11
12 # First make import warnings look like they're coming from the "use".
13 local $SIG{__WARN__} = sub {
14 my $text = shift;
2b5b2650 15 $text =~ s/ at \S*Exporter.pm line \d+.*\n//;
748a9306
LW
16 local $Carp::CarpLevel = 1; # ignore package calling us too.
17 Carp::carp($text);
18 };
4633a7c4
LW
19 local $SIG{__DIE__} = sub {
20 Carp::croak("$_[0]Illegal null symbol in \@${1}::EXPORT")
21 if $_[0] =~ /^Unable to create sub named "(.*?)::"/;
22 };
748a9306 23
2b5b2650
PP
24 my($pkg, $callpkg, @imports) = @_;
25 my($type, $sym, $oops);
26 *exports = *{"${pkg}::EXPORT"};
27
8990e307 28 if (@imports) {
8990e307
LW
29 if (!%exports) {
30 grep(s/^&//, @exports);
2b5b2650
PP
31 @exports{@exports} = (1) x @exports;
32 my $ok = \@{"${pkg}::EXPORT_OK"};
33 if (@$ok) {
34 grep(s/^&//, @$ok);
35 @exports{@$ok} = (1) x @$ok;
a0d0e21e 36 }
8990e307 37 }
748a9306
LW
38
39 if ($imports[0] =~ m#^[/!:]#){
748a9306
LW
40 my $tagsref = \%{"${pkg}::EXPORT_TAGS"};
41 my $tagdata;
42 my %imports;
2b5b2650 43 my($remove, $spec, @names, @allexports);
748a9306 44 # negated first item implies starting with default set:
2b5b2650
PP
45 unshift @imports, ':DEFAULT' if $imports[0] =~ m/^!/;
46 foreach $spec (@imports){
47 $remove = $spec =~ s/^!//;
748a9306 48
2b5b2650
PP
49 if ($spec =~ s/^://){
50 if ($spec eq 'DEFAULT'){
748a9306
LW
51 @names = @exports;
52 }
2b5b2650 53 elsif ($tagdata = $tagsref->{$spec}) {
748a9306
LW
54 @names = @$tagdata;
55 }
2b5b2650
PP
56 else {
57 warn qq["$spec" is not defined in %${pkg}::EXPORT_TAGS];
58 ++$oops;
59 next;
60 }
61 }
62 elsif ($spec =~ m:^/(.*)/$:){
63 my $patn = $1;
64 @allexports = keys %exports unless @allexports; # only do keys once
65 @names = grep(/$patn/, @allexports); # not anchored by default
748a9306 66 }
2b5b2650
PP
67 else {
68 @names = ($spec); # is a normal symbol name
69 }
70
71 warn "Import ".($remove ? "del":"add").": @names "
72 if $Verbose;
748a9306 73
2b5b2650
PP
74 if ($remove) {
75 foreach $sym (@names) { delete $imports{$sym} }
748a9306
LW
76 }
77 else {
2b5b2650 78 @imports{@names} = (1) x @names;
748a9306
LW
79 }
80 }
81 @imports = keys %imports;
82 }
83
8990e307
LW
84 foreach $sym (@imports) {
85 if (!$exports{$sym}) {
e50aee73
AD
86 if ($sym =~ m/^\d/) {
87 $pkg->require_version($sym);
88 # If the version number was the only thing specified
89 # then we should act as if nothing was specified:
90 if (@imports == 1) {
91 @imports = @exports;
92 last;
93 }
94 } elsif ($sym !~ s/^&// || !$exports{$sym}) {
2b5b2650 95 warn qq["$sym" is not exported by the $pkg module];
8990e307 96 $oops++;
8990e307
LW
97 }
98 }
99 }
2b5b2650 100 Carp::croak("Can't continue after import errors") if $oops;
8990e307
LW
101 }
102 else {
103 @imports = @exports;
104 }
2b5b2650
PP
105
106 *fail = *{"${pkg}::EXPORT_FAIL"};
107 if (@fail) {
108 if (!%fail) {
109 # Build cache of symbols. Optimise the lookup by adding
110 # barewords twice... both with and without a leading &.
111 # (Technique could be applied to %exports cache at cost of memory)
112 my @expanded = map { /^\w/ ? ($_, '&'.$_) : $_ } @fail;
113 warn "${pkg}::EXPORT_FAIL cached: @expanded" if $Verbose;
114 @fail{@expanded} = (1) x @expanded;
115 }
116 my @failed;
117 foreach $sym (@imports) { push(@failed, $sym) if $fail{$sym} }
118 if (@failed) {
119 @failed = $pkg->export_fail(@failed);
120 foreach $sym (@failed) {
121 warn qq["$sym" is not implemented by the $pkg module ],
122 "on this architecture";
123 }
124 Carp::croak("Can't continue after import errors") if @failed;
125 }
126 }
127
c07a80fd 128 warn "Importing into $callpkg from $pkg: ",
2b5b2650
PP
129 join(", ",sort @imports) if $Verbose;
130
8990e307 131 foreach $sym (@imports) {
2b5b2650
PP
132 # shortcut for the common case of no type character
133 (*{"${callpkg}::$sym"} = \&{"${pkg}::$sym"}, next)
134 unless $sym =~ s/^(\W)//;
135 $type = $1;
748a9306
LW
136 *{"${callpkg}::$sym"} =
137 $type eq '&' ? \&{"${pkg}::$sym"} :
138 $type eq '$' ? \${"${pkg}::$sym"} :
139 $type eq '@' ? \@{"${pkg}::$sym"} :
140 $type eq '%' ? \%{"${pkg}::$sym"} :
141 $type eq '*' ? *{"${pkg}::$sym"} :
2b5b2650 142 Carp::croak("Can't export symbol: $type$sym");
8990e307 143 }
2b5b2650 144}
8990e307 145
a0d0e21e 146sub import {
748a9306 147 my $pkg = shift;
2b5b2650 148 my $callpkg = caller($ExportLevel);
748a9306
LW
149 export $pkg, $callpkg, @_;
150}
151
2b5b2650
PP
152
153# Utility functions
154
155sub _push_tags {
156 my($pkg, $var, $syms) = @_;
157 my $nontag;
c07a80fd 158 *export_tags = \%{"${pkg}::EXPORT_TAGS"};
2b5b2650
PP
159 push(@{"${pkg}::$var"},
160 map { $export_tags{$_} ? @{$export_tags{$_}} : scalar(++$nontag,$_) }
161 (@$syms) ? @$syms : keys %export_tags);
162 # This may change to a die one day
163 Carp::carp("Some names are not tags") if $nontag and $^W;
164}
165
166sub export_tags { _push_tags((caller)[0], "EXPORT", \@_) }
167sub export_ok_tags { _push_tags((caller)[0], "EXPORT_OK", \@_) }
168
169
170# Default methods
171
172sub export_fail {
173 @_;
a0d0e21e
LW
174}
175
e50aee73
AD
176sub require_version {
177 my($self, $wanted) = @_;
178 my $pkg = ref $self || $self;
179 my $version = ${"${pkg}::VERSION"} || "(undef)";
180 Carp::croak("$pkg $wanted required--this is only version $version")
181 if $version < $wanted;
182 $version;
183}
184
8990e307 1851;
2b5b2650
PP
186
187# A simple self test harness. Change 'require Carp' to 'use Carp ()' for testing.
188# package main; eval(join('',<DATA>)) or die $@ unless caller;
189__END__
190package Test;
191$INC{'Exporter.pm'} = 1;
192@ISA = qw(Exporter);
193@EXPORT = qw(A1 A2 A3 A4 A5);
194@EXPORT_OK = qw(B1 B2 B3 B4 B5);
195%EXPORT_TAGS = (T1=>[qw(A1 A2 B1 B2)], T2=>[qw(A1 A2 B3 B4)], T3=>[qw(X3)]);
196@EXPORT_FAIL = qw(B4);
197Exporter::export_ok_tags('T3', 'unknown_tag');
198sub export_fail {
199 map { "Test::$_" } @_ # edit symbols just as an example
200}
201
202package main;
203$Exporter::Verbose = 1;
204#import Test;
205#import Test qw(X3); # export ok via export_ok_tags()
206#import Test qw(:T1 !A2 /5/ !/3/ B5);
207import Test qw(:T2 !B4);
208import Test qw(:T2); # should fail
2091;
210
211=head1 NAME
212
213Exporter - Implements default import method for modules
214
215=head1 SYNOPSIS
216
217In module ModuleName.pm:
218
219 package ModuleName;
220 require Exporter;
221 @ISA = qw(Exporter);
222
223 @EXPORT = qw(...); # symbols to export by default
224 @EXPORT_OK = qw(...); # symbols to export on request
225 %EXPORT_TAGS = tag => [...]; # define names for sets of symbols
226
227In other files which wish to use ModuleName:
228
229 use ModuleName; # import default symbols into my package
230
231 use ModuleName qw(...); # import listed symbols into my package
232
233 use ModuleName (); # do not import any symbols
234
235=head1 DESCRIPTION
236
237The Exporter module implements a default C<import> method which
238many modules choose inherit rather than implement their own.
239
240Perl automatically calls the C<import> method when processing a
241C<use> statement for a module. Modules and C<use> are documented
242in L<perlfunc> and L<perlmod>. Understanding the concept of
243modules and how the C<use> statement operates is important to
244understanding the Exporter.
245
246=head2 Selecting What To Export
247
248Do B<not> export method names!
249
250Do B<not> export anything else by default without a good reason!
251
252Exports pollute the namespace of the module user. If you must export
253try to use @EXPORT_OK in preference to @EXPORT and avoid short or
254common symbol names to reduce the risk of name clashes.
255
256Generally anything not exported is still accessible from outside the
257module using the ModuleName::item_name (or $blessed_ref->method)
258syntax. By convention you can use a leading underscore on names to
259informally indicate that they are 'internal' and not for public use.
260
261(It is actually possible to get private functions by saying:
262
263 my $subref = sub { ... };
264 &$subref;
265
266But there's no way to call that directly as a method, since a method
267must have a name in the symbol table.)
268
269As a general rule, if the module is trying to be object oriented
270then export nothing. If it's just a collection of functions then
271@EXPORT_OK anything but use @EXPORT with caution.
272
273Other module design guidelines can be found in L<perlmod>.
274
275=head2 Specialised Import Lists
276
277If the first entry in an import list begins with !, : or / then the
278list is treated as a series of specifications which either add to or
279delete from the list of names to import. They are processed left to
280right. Specifications are in the form:
281
282 [!]name This name only
283 [!]:DEFAULT All names in @EXPORT
284 [!]:tag All names in $EXPORT_TAGS{tag} anonymous list
285 [!]/pattern/ All names in @EXPORT and @EXPORT_OK which match
286
287A leading ! indicates that matching names should be deleted from the
288list of names to import. If the first specification is a deletion it
289is treated as though preceded by :DEFAULT. If you just want to import
290extra names in addition to the default set you will still need to
291include :DEFAULT explicitly.
292
293e.g., Module.pm defines:
294
295 @EXPORT = qw(A1 A2 A3 A4 A5);
296 @EXPORT_OK = qw(B1 B2 B3 B4 B5);
297 %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);
298
299 Note that you cannot use tags in @EXPORT or @EXPORT_OK.
300 Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.
301
302An application using Module can say something like:
303
304 use Module qw(:DEFAULT :T2 !B3 A3);
305
306Other examples include:
307
308 use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
309 use POSIX qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);
310
311Remember that most patterns (using //) will need to be anchored
312with a leading ^, e.g., C</^EXIT/> rather than C</EXIT/>.
313
314You can say C<BEGIN { $Exporter::Verbose=1 }> to see how the
315specifications are being processed and what is actually being imported
316into modules.
317
318=head2 Module Version Checking
319
320The Exporter module will convert an attempt to import a number from a
321module into a call to $module_name->require_version($value). This can
322be used to validate that the version of the module being used is
323greater than or equal to the required version.
324
325The Exporter module supplies a default require_version method which
326checks the value of $VERSION in the exporting module.
327
328Since the default require_version method treats the $VERSION number as
d5e40bcc
PP
329a simple numeric value it will regard version 1.10 as lower than
3301.9. For this reason it is strongly recommended that you use numbers
331with at least two decimal places, e.g., 1.09.
2b5b2650
PP
332
333=head2 Managing Unknown Symbols
334
335In some situations you may want to prevent certain symbols from being
336exported. Typically this applies to extensions which have functions
337or constants that may not exist on some systems.
338
339The names of any symbols that cannot be exported should be listed
340in the C<@EXPORT_FAIL> array.
341
342If a module attempts to import any of these symbols the Exporter will
343will give the module an opportunity to handle the situation before
344generating an error. The Exporter will call an export_fail method
345with a list of the failed symbols:
346
347 @failed_symbols = $module_name->export_fail(@failed_symbols);
348
349If the export_fail method returns an empty list then no error is
350recorded and all the requested symbols are exported. If the returned
351list is not empty then an error is generated for each symbol and the
352export fails. The Exporter provides a default export_fail method which
353simply returns the list unchanged.
354
355Uses for the export_fail method include giving better error messages
356for some symbols and performing lazy architectural checks (put more
357symbols into @EXPORT_FAIL by default and then take them out if someone
358actually tries to use them and an expensive check shows that they are
359usable on that platform).
360
361=head2 Tag Handling Utility Functions
362
363Since the symbols listed within %EXPORT_TAGS must also appear in either
364@EXPORT or @EXPORT_OK, two utility functions are provided which allow
365you to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK:
366
367 %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
368
369 Exporter::export_tags('foo'); # add aa, bb and cc to @EXPORT
370 Exporter::export_ok_tags('bar'); # add aa, cc and dd to @EXPORT_OK
371
372Any names which are not tags are added to @EXPORT or @EXPORT_OK
d5e40bcc 373unchanged but will trigger a warning (with C<-w>) to avoid misspelt tags
2b5b2650
PP
374names being silently added to @EXPORT or @EXPORT_OK. Future versions
375may make this a fatal error.
376
377=cut