1package Exporter; 2 3use strict; 4no strict 'refs'; 5 6our $Debug = 0; 7our $ExportLevel = 0; 8our $Verbose ||= 0; 9our $VERSION = '5.78'; 10our %Cache; 11 12sub as_heavy { 13 require Exporter::Heavy; 14 # Unfortunately, this does not work if the caller is aliased as *name = \&foo 15 # Thus the need to create a lot of identical subroutines 16 my $c = (caller(1))[3]; 17 $c =~ s/.*:://; 18 \&{"Exporter::Heavy::heavy_$c"}; 19} 20 21sub export { 22 goto &{as_heavy()}; 23} 24 25sub import { 26 my $pkg = shift; 27 my $callpkg = caller($ExportLevel); 28 29 if ($pkg eq "Exporter" and @_ and $_[0] eq "import") { 30 *{$callpkg."::import"} = \&import; 31 return; 32 } 33 34 # We *need* to treat @{"$pkg\::EXPORT_FAIL"} since Carp uses it :-( 35 my $exports = \@{"$pkg\::EXPORT"}; 36 # But, avoid creating things if they don't exist, which saves a couple of 37 # hundred bytes per package processed. 38 my $fail = ${$pkg . '::'}{EXPORT_FAIL} && \@{"$pkg\::EXPORT_FAIL"}; 39 return export $pkg, $callpkg, @_ 40 if $Verbose or $Debug or $fail && @$fail > 1; 41 my $export_cache = ($Cache{$pkg} ||= {}); 42 my $args = @_ or @_ = @$exports; 43 44 if ($args and not %$export_cache) { 45 s/^&//, $export_cache->{$_} = 1 46 foreach (@$exports, @{"$pkg\::EXPORT_OK"}); 47 } 48 my $heavy; 49 # Try very hard not to use {} and hence have to enter scope on the foreach 50 # We bomb out of the loop with last as soon as heavy is set. 51 if ($args or $fail) { 52 ($heavy = (/\W/ or $args and not exists $export_cache->{$_} 53 or $fail and @$fail and $_ eq $fail->[0])) and last 54 foreach (@_); 55 } else { 56 ($heavy = /\W/) and last 57 foreach (@_); 58 } 59 return export $pkg, $callpkg, ($args ? @_ : ()) if $heavy; 60 local $SIG{__WARN__} = 61 sub {require Carp; &Carp::carp} if not $SIG{__WARN__}; 62 # shortcut for the common case of no type character 63 *{"$callpkg\::$_"} = \&{"$pkg\::$_"} foreach @_; 64} 65 66# Default methods 67 68sub export_fail { 69 my $self = shift; 70 @_; 71} 72 73# Unfortunately, caller(1)[3] "does not work" if the caller is aliased as 74# *name = \&foo. Thus the need to create a lot of identical subroutines 75# Otherwise we could have aliased them to export(). 76 77sub export_to_level { 78 goto &{as_heavy()}; 79} 80 81sub export_tags { 82 goto &{as_heavy()}; 83} 84 85sub export_ok_tags { 86 goto &{as_heavy()}; 87} 88 89sub require_version { 90 goto &{as_heavy()}; 91} 92 931; 94__END__ 95 96=head1 NAME 97 98Exporter - Implements default import method for modules 99 100=head1 SYNOPSIS 101 102In module F<YourModule.pm>: 103 104 package YourModule; 105 use Exporter 'import'; 106 our @EXPORT_OK = qw(munge frobnicate); # symbols to export on request 107 108or 109 110 package YourModule; 111 require Exporter; 112 our @ISA = qw(Exporter); # inherit all of Exporter's methods 113 our @EXPORT_OK = qw(munge frobnicate); # symbols to export on request 114 115or 116 117 package YourModule; 118 use parent 'Exporter'; # inherit all of Exporter's methods 119 our @EXPORT_OK = qw(munge frobnicate); # symbols to export on request 120 121In other files which wish to use C<YourModule>: 122 123 use YourModule qw(frobnicate); # import listed symbols 124 frobnicate ($left, $right) # calls YourModule::frobnicate 125 126Take a look at L</Good Practices> for some variants 127you will like to use in modern Perl code. 128 129=head1 DESCRIPTION 130 131The Exporter module implements an C<import> method which allows a module 132to export functions and variables to its users' namespaces. Many modules 133use Exporter rather than implementing their own C<import> method because 134Exporter provides a highly flexible interface, with an implementation optimised 135for the common case. 136 137Perl automatically calls the C<import> method when processing a 138C<use> statement for a module. Modules and C<use> are documented 139in L<perlfunc> and L<perlmod>. Understanding the concept of 140modules and how the C<use> statement operates is important to 141understanding the Exporter. 142 143=head2 How to Export 144 145The arrays C<@EXPORT> and C<@EXPORT_OK> in a module hold lists of 146symbols that are going to be exported into the users name space by 147default, or which they can request to be exported, respectively. The 148symbols can represent functions, scalars, arrays, hashes, or typeglobs. 149The symbols must be given by full name with the exception that the 150ampersand in front of a function is optional, e.g. 151 152 our @EXPORT = qw(afunc $scalar @array); # afunc is a function 153 our @EXPORT_OK = qw(&bfunc %hash *typeglob); # explicit prefix on &bfunc 154 155If you are only exporting function names it is recommended to omit the 156ampersand, as the implementation is faster this way. 157 158=head2 Selecting What to Export 159 160Do B<not> export method names! 161 162Do B<not> export anything else by default without a good reason! 163 164Exports pollute the namespace of the module user. If you must export 165try to use C<@EXPORT_OK> in preference to C<@EXPORT> and avoid short or 166common symbol names to reduce the risk of name clashes. 167 168Generally anything not exported is still accessible from outside the 169module using the C<YourModule::item_name> (or C<< $blessed_ref->method >>) 170syntax. By convention you can use a leading underscore on names to 171informally indicate that they are 'internal' and not for public use. 172 173(It is actually possible to get private functions by saying: 174 175 my $subref = sub { ... }; 176 $subref->(@args); # Call it as a function 177 $obj->$subref(@args); # Use it as a method 178 179However if you use them for methods it is up to you to figure out 180how to make inheritance work.) 181 182As a general rule, if the module is trying to be object oriented 183then export nothing. If it's just a collection of functions then 184C<@EXPORT_OK> anything but use C<@EXPORT> with caution. For function and 185method names use barewords in preference to names prefixed with 186ampersands for the export lists. 187 188Other module design guidelines can be found in L<perlmod>. 189 190=head2 How to Import 191 192In other files which wish to use your module there are three basic ways for 193them to load your module and import its symbols: 194 195=over 4 196 197=item C<use YourModule;> 198 199This imports all the symbols from YourModule's C<@EXPORT> into the namespace 200of the C<use> statement. 201 202=item C<use YourModule ();> 203 204This causes perl to load your module but does not import any symbols. 205 206=item C<use YourModule qw(...);> 207 208This imports only the symbols listed by the caller into their namespace. 209All listed symbols must be in your C<@EXPORT> or C<@EXPORT_OK>, else an error 210occurs. The advanced export features of Exporter are accessed like this, 211but with list entries that are syntactically distinct from symbol names. 212 213=back 214 215Unless you want to use its advanced features, this is probably all you 216need to know to use Exporter. 217 218=head1 Advanced Features 219 220=head2 Specialised Import Lists 221 222If any of the entries in an import list begins with !, : or / then 223the list is treated as a series of specifications which either add to 224or delete from the list of names to import. They are processed left to 225right. Specifications are in the form: 226 227 [!]name This name only 228 [!]:DEFAULT All names in @EXPORT 229 [!]:tag All names in $EXPORT_TAGS{tag} anonymous array 230 [!]/pattern/ All names in @EXPORT and @EXPORT_OK which match 231 232A leading ! indicates that matching names should be deleted from the 233list of names to import. If the first specification is a deletion it 234is treated as though preceded by :DEFAULT. If you just want to import 235extra names in addition to the default set you will still need to 236include :DEFAULT explicitly. 237 238e.g., F<Module.pm> defines: 239 240 our @EXPORT = qw(A1 A2 A3 A4 A5); 241 our @EXPORT_OK = qw(B1 B2 B3 B4 B5); 242 our %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]); 243 244Note that you cannot use tags in @EXPORT or @EXPORT_OK. 245 246Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK. 247 248An application using Module can say something like: 249 250 use Module qw(:DEFAULT :T2 !B3 A3); 251 252Other examples include: 253 254 use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET); 255 use POSIX qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/); 256 257Remember that most patterns (using //) will need to be anchored 258with a leading ^, e.g., C</^EXIT/> rather than C</EXIT/>. 259 260You can say C<BEGIN { $Exporter::Verbose=1 }> to see how the 261specifications are being processed and what is actually being imported 262into modules. 263 264=head2 Exporting Without Using Exporter's import Method 265 266Exporter has a special method, 'export_to_level' which is used in situations 267where you can't directly call Exporter's 268import method. The export_to_level 269method looks like: 270 271 MyPackage->export_to_level( 272 $where_to_export, $package, @what_to_export 273 ); 274 275where C<$where_to_export> is an integer telling how far up the calling stack 276to export your symbols, and C<@what_to_export> is an array telling what 277symbols *to* export (usually this is C<@_>). The C<$package> argument is 278currently unused. 279 280For example, suppose that you have a module, A, which already has an 281import function: 282 283 package A; 284 285 our @ISA = qw(Exporter); 286 our @EXPORT_OK = qw($b); 287 288 sub import 289 { 290 $A::b = 1; # not a very useful import method 291 } 292 293and you want to Export symbol C<$A::b> back to the module that called 294package A. Since Exporter relies on the import method to work, via 295inheritance, as it stands Exporter::import() will never get called. 296Instead, say the following: 297 298 package A; 299 our @ISA = qw(Exporter); 300 our @EXPORT_OK = qw($b); 301 302 sub import 303 { 304 $A::b = 1; 305 A->export_to_level(1, @_); 306 } 307 308This will export the symbols one level 'above' the current package - ie: to 309the program or module that used package A. 310 311Note: Be careful not to modify C<@_> at all before you call export_to_level 312- or people using your package will get very unexplained results! 313 314=head2 Exporting Without Inheriting from Exporter 315 316By including Exporter in your C<@ISA> you inherit an Exporter's import() method 317but you also inherit several other helper methods which you probably don't 318want and complicate the inheritance tree. To avoid this you can do: 319 320 package YourModule; 321 use Exporter qw(import); 322 323which will export Exporter's own import() method into YourModule. 324Everything will work as before but you won't need to include Exporter in 325C<@YourModule::ISA>. 326 327Note: This feature was introduced in version 5.57 328of Exporter, released with perl 5.8.3. 329 330=head2 Module Version Checking 331 332The Exporter module will convert an attempt to import a number from a 333module into a call to C<< $module_name->VERSION($value) >>. This can 334be used to validate that the version of the module being used is 335greater than or equal to the required version. 336 337For historical reasons, Exporter supplies a C<require_version> method that 338simply delegates to C<VERSION>. Originally, before C<UNIVERSAL::VERSION> 339existed, Exporter would call C<require_version>. 340 341Since the C<UNIVERSAL::VERSION> method treats the C<$VERSION> number as 342a simple numeric value it will regard version 1.10 as lower than 3431.9. For this reason it is strongly recommended that you use numbers 344with at least two decimal places, e.g., 1.09. 345 346=head2 Managing Unknown Symbols 347 348In some situations you may want to prevent certain symbols from being 349exported. Typically this applies to extensions which have functions 350or constants that may not exist on some systems. 351 352The names of any symbols that cannot be exported should be listed 353in the C<@EXPORT_FAIL> array. 354 355If a module attempts to import any of these symbols the Exporter 356will give the module an opportunity to handle the situation before 357generating an error. The Exporter will call an export_fail method 358with a list of the failed symbols: 359 360 @failed_symbols = $module_name->export_fail(@failed_symbols); 361 362If the C<export_fail> method returns an empty list then no error is 363recorded and all the requested symbols are exported. If the returned 364list is not empty then an error is generated for each symbol and the 365export fails. The Exporter provides a default C<export_fail> method which 366simply returns the list unchanged. 367 368Uses for the C<export_fail> method include giving better error messages 369for some symbols and performing lazy architectural checks (put more 370symbols into C<@EXPORT_FAIL> by default and then take them out if someone 371actually tries to use them and an expensive check shows that they are 372usable on that platform). 373 374=head2 Tag Handling Utility Functions 375 376Since the symbols listed within C<%EXPORT_TAGS> must also appear in either 377C<@EXPORT> or C<@EXPORT_OK>, two utility functions are provided which allow 378you to easily add tagged sets of symbols to C<@EXPORT> or C<@EXPORT_OK>: 379 380 our %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]); 381 382 Exporter::export_tags('foo'); # add aa, bb and cc to @EXPORT 383 Exporter::export_ok_tags('bar'); # add aa, cc and dd to @EXPORT_OK 384 385Any names which are not tags are added to C<@EXPORT> or C<@EXPORT_OK> 386unchanged but will trigger a warning (with C<-w>) to avoid misspelt tags 387names being silently added to C<@EXPORT> or C<@EXPORT_OK>. Future versions 388may make this a fatal error. 389 390=head2 Generating Combined Tags 391 392If several symbol categories exist in C<%EXPORT_TAGS>, it's usually 393useful to create the utility ":all" to simplify "use" statements. 394 395The simplest way to do this is: 396 397 our %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]); 398 399 # add all the other ":class" tags to the ":all" class, 400 # deleting duplicates 401 { 402 my %seen; 403 404 push @{$EXPORT_TAGS{all}}, 405 grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS; 406 } 407 408F<CGI.pm> creates an ":all" tag which contains some (but not really 409all) of its categories. That could be done with one small 410change: 411 412 # add some of the other ":class" tags to the ":all" class, 413 # deleting duplicates 414 { 415 my %seen; 416 417 push @{$EXPORT_TAGS{all}}, 418 grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} 419 foreach qw/html2 html3 netscape form cgi internal/; 420 } 421 422Note that the tag names in C<%EXPORT_TAGS> don't have the leading ':'. 423 424=head2 C<AUTOLOAD>ed Constants 425 426Many modules make use of C<AUTOLOAD>ing for constant subroutines to 427avoid having to compile and waste memory on rarely used values (see 428L<perlsub> for details on constant subroutines). Calls to such 429constant subroutines are not optimized away at compile time because 430they can't be checked at compile time for constancy. 431 432Even if a prototype is available at compile time, the body of the 433subroutine is not (it hasn't been C<AUTOLOAD>ed yet). perl needs to 434examine both the C<()> prototype and the body of a subroutine at 435compile time to detect that it can safely replace calls to that 436subroutine with the constant value. 437 438A workaround for this is to call the constants once in a C<BEGIN> block: 439 440 package My ; 441 442 use Socket ; 443 444 foo( SO_LINGER ); ## SO_LINGER NOT optimized away; called at runtime 445 BEGIN { SO_LINGER } 446 foo( SO_LINGER ); ## SO_LINGER optimized away at compile time. 447 448This forces the C<AUTOLOAD> for C<SO_LINGER> to take place before 449SO_LINGER is encountered later in C<My> package. 450 451If you are writing a package that C<AUTOLOAD>s, consider forcing 452an C<AUTOLOAD> for any constants explicitly imported by other packages 453or which are usually used when your package is C<use>d. 454 455=head1 Good Practices 456 457=head2 Declaring C<@EXPORT_OK> and Friends 458 459When using C<Exporter> with the standard C<strict> and C<warnings> 460pragmas, the C<our> keyword is needed to declare the package 461variables C<@EXPORT_OK>, C<@EXPORT>, C<@ISA>, etc. 462 463 our @ISA = qw(Exporter); 464 our @EXPORT_OK = qw(munge frobnicate); 465 466If backward compatibility for Perls B<under> 5.6 is important, 467one must write instead a C<use vars> statement. 468 469 use vars qw(@ISA @EXPORT_OK); 470 @ISA = qw(Exporter); 471 @EXPORT_OK = qw(munge frobnicate); 472 473=head2 Playing Safe 474 475There are some caveats with the use of runtime statements 476like C<require Exporter> and the assignment to package 477variables, which can be very subtle for the unaware programmer. 478This may happen for instance with mutually recursive 479modules, which are affected by the time the relevant 480constructions are executed. 481 482The ideal way to never have to think about that is to use 483C<BEGIN> blocks and the simple import method. So the first part 484of the L</SYNOPSIS> code could be rewritten as: 485 486 package YourModule; 487 488 use strict; 489 use warnings; 490 491 use Exporter 'import'; 492 BEGIN { 493 our @EXPORT_OK = qw(munge frobnicate); # symbols to export on request 494 } 495 496Or if you need to inherit from Exporter: 497 498 package YourModule; 499 500 use strict; 501 use warnings; 502 503 BEGIN { 504 require Exporter; 505 our @ISA = qw(Exporter); # inherit all of Exporter's methods 506 our @EXPORT_OK = qw(munge frobnicate); # symbols to export on request 507 } 508 509The C<BEGIN> will assure that the loading of F<Exporter.pm> 510and the assignments to C<@ISA> and C<@EXPORT_OK> happen 511immediately like C<use>, leaving no room for something to get awry 512or just plain wrong. 513 514With respect to loading C<Exporter> and inheriting, there 515are alternatives with the use of modules like C<base> and C<parent>. 516 517 use base qw(Exporter); 518 # or 519 use parent qw(Exporter); 520 521Any of these statements are nice replacements for 522C<BEGIN { require Exporter; our @ISA = qw(Exporter); }> 523with the same compile-time effect. The basic difference 524is that C<base> code interacts with declared C<fields> 525while C<parent> is a streamlined version of the older 526C<base> code to just establish the IS-A relationship. 527 528For more details, see the documentation and code of 529L<base> and L<parent>. 530 531Another thorough remedy to that runtime 532vs. compile-time trap is to use L<Exporter::Easy>, 533which is a wrapper of Exporter that allows all 534boilerplate code at a single gulp in the 535use statement. 536 537 use Exporter::Easy ( 538 OK => [ qw(munge frobnicate) ], 539 ); 540 # @ISA setup is automatic 541 # all assignments happen at compile time 542 543=head2 What Not to Export 544 545You have been warned already in L</Selecting What to Export> 546to not export: 547 548=over 4 549 550=item * 551 552method names (because you don't need to 553and that's likely to not do what you want), 554 555=item * 556 557anything by default (because you don't want to surprise your users... 558badly) 559 560=item * 561 562anything you don't need to (because less is more) 563 564=back 565 566There's one more item to add to this list. Do B<not> 567export variable names. Just because C<Exporter> lets you 568do that, it does not mean you should. 569 570 @EXPORT_OK = qw($svar @avar %hvar); # DON'T! 571 572Exporting variables is not a good idea. They can 573change under the hood, provoking horrible 574effects at-a-distance that are too hard to track 575and to fix. Trust me: they are not worth it. 576 577To provide the capability to set/get class-wide 578settings, it is best instead to provide accessors 579as subroutines or class methods instead. 580 581=head1 SEE ALSO 582 583C<Exporter> is definitely not the only module with 584symbol exporter capabilities. At CPAN, you may find 585a bunch of them. Some are lighter. Some 586provide improved APIs and features. Pick the one 587that fits your needs. The following is 588a sample list of such modules. 589 590 Exporter::Easy 591 Exporter::Lite 592 Exporter::Renaming 593 Exporter::Tidy 594 Sub::Exporter / Sub::Installer 595 Perl6::Export / Perl6::Export::Attrs 596 597=head1 LICENSE 598 599This library is free software. You can redistribute it 600and/or modify it under the same terms as Perl itself. 601 602=cut 603 604 605 606