Exporter.pm 18 KB

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