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