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