1Exporter(3)           User Contributed Perl Documentation          Exporter(3)
2
3
4

NAME

6       Exporter - Implements default import method for modules
7

SYNOPSIS

9       In module YourModule.pm:
10
11         package YourModule;
12         require Exporter;
13         @ISA = qw(Exporter);
14         @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
15
16       or
17
18         package YourModule;
19         use Exporter 'import'; # gives you Exporter's import() method directly
20         @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
21
22       In other files which wish to use "YourModule":
23
24         use YourModule qw(frobnicate);      # import listed symbols
25         frobnicate ($left, $right)          # calls YourModule::frobnicate
26
27       Take a look at "Good Practices" for some variants you will like to use
28       in modern Perl code.
29

DESCRIPTION

31       The Exporter module implements an "import" method which allows a module
32       to export functions and variables to its users' namespaces.  Many
33       modules use Exporter rather than implementing their own "import" method
34       because Exporter provides a highly flexible interface, with an
35       implementation optimised for the common case.
36
37       Perl automatically calls the "import" method when processing a "use"
38       statement for a module.  Modules and "use" are documented in perlfunc
39       and perlmod.  Understanding the concept of modules and how the "use"
40       statement operates is important to understanding the Exporter.
41
42   How to Export
43       The arrays @EXPORT and @EXPORT_OK in a module hold lists of symbols
44       that are going to be exported into the users name space by default, or
45       which they can request to be exported, respectively.  The symbols can
46       represent functions, scalars, arrays, hashes, or typeglobs.  The
47       symbols must be given by full name with the exception that the
48       ampersand in front of a function is optional, e.g.
49
50           @EXPORT    = qw(afunc $scalar @array);   # afunc is a function
51           @EXPORT_OK = qw(&bfunc %hash *typeglob); # explicit prefix on &bfunc
52
53       If you are only exporting function names it is recommended to omit the
54       ampersand, as the implementation is faster this way.
55
56   Selecting What to Export
57       Do not export method names!
58
59       Do not export anything else by default without a good reason!
60
61       Exports pollute the namespace of the module user.  If you must export
62       try to use @EXPORT_OK in preference to @EXPORT and avoid short or
63       common symbol names to reduce the risk of name clashes.
64
65       Generally anything not exported is still accessible from outside the
66       module using the "YourModule::item_name" (or "$blessed_ref->method")
67       syntax.  By convention you can use a leading underscore on names to
68       informally indicate that they are 'internal' and not for public use.
69
70       (It is actually possible to get private functions by saying:
71
72         my $subref = sub { ... };
73         $subref->(@args);            # Call it as a function
74         $obj->$subref(@args);        # Use it as a method
75
76       However if you use them for methods it is up to you to figure out how
77       to make inheritance work.)
78
79       As a general rule, if the module is trying to be object oriented then
80       export nothing.  If it's just a collection of functions then @EXPORT_OK
81       anything but use @EXPORT with caution.  For function and method names
82       use barewords in preference to names prefixed with ampersands for the
83       export lists.
84
85       Other module design guidelines can be found in perlmod.
86
87   How to Import
88       In other files which wish to use your module there are three basic ways
89       for them to load your module and import its symbols:
90
91       "use YourModule;"
92           This imports all the symbols from YourModule's @EXPORT into the
93           namespace of the "use" statement.
94
95       "use YourModule ();"
96           This causes perl to load your module but does not import any
97           symbols.
98
99       "use YourModule qw(...);"
100           This imports only the symbols listed by the caller into their
101           namespace.  All listed symbols must be in your @EXPORT or
102           @EXPORT_OK, else an error occurs.  The advanced export features of
103           Exporter are accessed like this, but with list entries that are
104           syntactically distinct from symbol names.
105
106       Unless you want to use its advanced features, this is probably all you
107       need to know to use Exporter.
108

Advanced Features

110   Specialised Import Lists
111       If any of the entries in an import list begins with !, : or / then the
112       list is treated as a series of specifications which either add to or
113       delete from the list of names to import.  They are processed left to
114       right. Specifications are in the form:
115
116           [!]name         This name only
117           [!]:DEFAULT     All names in @EXPORT
118           [!]:tag         All names in $EXPORT_TAGS{tag} anonymous array
119           [!]/pattern/    All names in @EXPORT and @EXPORT_OK which match
120
121       A leading ! indicates that matching names should be deleted from the
122       list of names to import.  If the first specification is a deletion it
123       is treated as though preceded by :DEFAULT.  If you just want to import
124       extra names in addition to the default set you will still need to
125       include :DEFAULT explicitly.
126
127       e.g., Module.pm defines:
128
129           @EXPORT      = qw(A1 A2 A3 A4 A5);
130           @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
131           %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);
132
133       Note that you cannot use tags in @EXPORT or @EXPORT_OK.
134
135       Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.
136
137       An application using Module can say something like:
138
139           use Module qw(:DEFAULT :T2 !B3 A3);
140
141       Other examples include:
142
143           use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
144           use POSIX  qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);
145
146       Remember that most patterns (using //) will need to be anchored with a
147       leading ^, e.g., "/^EXIT/" rather than "/EXIT/".
148
149       You can say "BEGIN { $Exporter::Verbose=1 }" to see how the
150       specifications are being processed and what is actually being imported
151       into modules.
152
153   Exporting Without Using Exporter's import Method
154       Exporter has a special method, 'export_to_level' which is used in
155       situations where you can't directly call Exporter's import method.  The
156       export_to_level method looks like:
157
158           MyPackage->export_to_level(
159               $where_to_export, $package, @what_to_export
160           );
161
162       where $where_to_export is an integer telling how far up the calling
163       stack to export your symbols, and @what_to_export is an array telling
164       what symbols *to* export (usually this is @_).  The $package argument
165       is currently unused.
166
167       For example, suppose that you have a module, A, which already has an
168       import function:
169
170           package A;
171
172           @ISA = qw(Exporter);
173           @EXPORT_OK = qw($b);
174
175           sub import
176           {
177               $A::b = 1;     # not a very useful import method
178           }
179
180       and you want to Export symbol $A::b back to the module that called
181       package A.  Since Exporter relies on the import method to work, via
182       inheritance, as it stands Exporter::import() will never get called.
183       Instead, say the following:
184
185           package A;
186           @ISA = qw(Exporter);
187           @EXPORT_OK = qw($b);
188
189           sub import
190           {
191               $A::b = 1;
192               A->export_to_level(1, @_);
193           }
194
195       This will export the symbols one level 'above' the current package -
196       ie: to the program or module that used package A.
197
198       Note: Be careful not to modify @_ at all before you call
199       export_to_level - or people using your package will get very
200       unexplained results!
201
202   Exporting Without Inheriting from Exporter
203       By including Exporter in your @ISA you inherit an Exporter's import()
204       method but you also inherit several other helper methods which you
205       probably don't want.  To avoid this you can do:
206
207         package YourModule;
208         use Exporter qw(import);
209
210       which will export Exporter's own import() method into YourModule.
211       Everything will work as before but you won't need to include Exporter
212       in @YourModule::ISA.
213
214       Note: This feature was introduced in version 5.57 of Exporter, released
215       with perl 5.8.3.
216
217   Module Version Checking
218       The Exporter module will convert an attempt to import a number from a
219       module into a call to "$module_name->VERSION($value)".  This can be
220       used to validate that the version of the module being used is greater
221       than or equal to the required version.
222
223       For historical reasons, Exporter supplies a "require_version" method
224       that simply delegates to "VERSION".  Originally, before
225       "UNIVERSAL::VERSION" existed, Exporter would call "require_version".
226
227       Since the "UNIVERSAL::VERSION" method treats the $VERSION number as a
228       simple numeric value it will regard version 1.10 as lower than 1.9.
229       For this reason it is strongly recommended that you use numbers with at
230       least two decimal places, e.g., 1.09.
231
232   Managing Unknown Symbols
233       In some situations you may want to prevent certain symbols from being
234       exported.  Typically this applies to extensions which have functions or
235       constants that may not exist on some systems.
236
237       The names of any symbols that cannot be exported should be listed in
238       the @EXPORT_FAIL array.
239
240       If a module attempts to import any of these symbols the Exporter will
241       give the module an opportunity to handle the situation before
242       generating an error.  The Exporter will call an export_fail method with
243       a list of the failed symbols:
244
245         @failed_symbols = $module_name->export_fail(@failed_symbols);
246
247       If the "export_fail" method returns an empty list then no error is
248       recorded and all the requested symbols are exported.  If the returned
249       list is not empty then an error is generated for each symbol and the
250       export fails.  The Exporter provides a default "export_fail" method
251       which simply returns the list unchanged.
252
253       Uses for the "export_fail" method include giving better error messages
254       for some symbols and performing lazy architectural checks (put more
255       symbols into @EXPORT_FAIL by default and then take them out if someone
256       actually tries to use them and an expensive check shows that they are
257       usable on that platform).
258
259   Tag Handling Utility Functions
260       Since the symbols listed within %EXPORT_TAGS must also appear in either
261       @EXPORT or @EXPORT_OK, two utility functions are provided which allow
262       you to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK:
263
264         %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
265
266         Exporter::export_tags('foo');     # add aa, bb and cc to @EXPORT
267         Exporter::export_ok_tags('bar');  # add aa, cc and dd to @EXPORT_OK
268
269       Any names which are not tags are added to @EXPORT or @EXPORT_OK
270       unchanged but will trigger a warning (with "-w") to avoid misspelt tags
271       names being silently added to @EXPORT or @EXPORT_OK.  Future versions
272       may make this a fatal error.
273
274   Generating Combined Tags
275       If several symbol categories exist in %EXPORT_TAGS, it's usually useful
276       to create the utility ":all" to simplify "use" statements.
277
278       The simplest way to do this is:
279
280         %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
281
282         # add all the other ":class" tags to the ":all" class,
283         # deleting duplicates
284         {
285           my %seen;
286
287           push @{$EXPORT_TAGS{all}},
288             grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;
289         }
290
291       CGI.pm creates an ":all" tag which contains some (but not really all)
292       of its categories.  That could be done with one small change:
293
294         # add some of the other ":class" tags to the ":all" class,
295         # deleting duplicates
296         {
297           my %seen;
298
299           push @{$EXPORT_TAGS{all}},
300             grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}
301               foreach qw/html2 html3 netscape form cgi internal/;
302         }
303
304       Note that the tag names in %EXPORT_TAGS don't have the leading ':'.
305
306   "AUTOLOAD"ed Constants
307       Many modules make use of "AUTOLOAD"ing for constant subroutines to
308       avoid having to compile and waste memory on rarely used values (see
309       perlsub for details on constant subroutines).  Calls to such constant
310       subroutines are not optimized away at compile time because they can't
311       be checked at compile time for constancy.
312
313       Even if a prototype is available at compile time, the body of the
314       subroutine is not (it hasn't been "AUTOLOAD"ed yet).  perl needs to
315       examine both the "()" prototype and the body of a subroutine at compile
316       time to detect that it can safely replace calls to that subroutine with
317       the constant value.
318
319       A workaround for this is to call the constants once in a "BEGIN" block:
320
321          package My ;
322
323          use Socket ;
324
325          foo( SO_LINGER );  ## SO_LINGER NOT optimized away; called at runtime
326          BEGIN { SO_LINGER }
327          foo( SO_LINGER );  ## SO_LINGER optimized away at compile time.
328
329       This forces the "AUTOLOAD" for "SO_LINGER" to take place before
330       SO_LINGER is encountered later in "My" package.
331
332       If you are writing a package that "AUTOLOAD"s, consider forcing an
333       "AUTOLOAD" for any constants explicitly imported by other packages or
334       which are usually used when your package is "use"d.
335

Good Practices

337   Declaring @EXPORT_OK and Friends
338       When using "Exporter" with the standard "strict" and "warnings"
339       pragmas, the "our" keyword is needed to declare the package variables
340       @EXPORT_OK, @EXPORT, @ISA, etc.
341
342         our @ISA = qw(Exporter);
343         our @EXPORT_OK = qw(munge frobnicate);
344
345       If backward compatibility for Perls under 5.6 is important, one must
346       write instead a "use vars" statement.
347
348         use vars qw(@ISA @EXPORT_OK);
349         @ISA = qw(Exporter);
350         @EXPORT_OK = qw(munge frobnicate);
351
352   Playing Safe
353       There are some caveats with the use of runtime statements like "require
354       Exporter" and the assignment to package variables, which can be very
355       subtle for the unaware programmer.  This may happen for instance with
356       mutually recursive modules, which are affected by the time the relevant
357       constructions are executed.
358
359       The ideal (but a bit ugly) way to never have to think about that is to
360       use "BEGIN" blocks.  So the first part of the "SYNOPSIS" code could be
361       rewritten as:
362
363         package YourModule;
364
365         use strict;
366         use warnings;
367
368         our (@ISA, @EXPORT_OK);
369         BEGIN {
370            require Exporter;
371            @ISA = qw(Exporter);
372            @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
373         }
374
375       The "BEGIN" will assure that the loading of Exporter.pm and the
376       assignments to @ISA and @EXPORT_OK happen immediately, leaving no room
377       for something to get awry or just plain wrong.
378
379       With respect to loading "Exporter" and inheriting, there are
380       alternatives with the use of modules like "base" and "parent".
381
382         use base qw(Exporter);
383         # or
384         use parent qw(Exporter);
385
386       Any of these statements are nice replacements for "BEGIN { require
387       Exporter; @ISA = qw(Exporter); }" with the same compile-time effect.
388       The basic difference is that "base" code interacts with declared
389       "fields" while "parent" is a streamlined version of the older "base"
390       code to just establish the IS-A relationship.
391
392       For more details, see the documentation and code of base and parent.
393
394       Another thorough remedy to that runtime vs. compile-time trap is to use
395       Exporter::Easy, which is a wrapper of Exporter that allows all
396       boilerplate code at a single gulp in the use statement.
397
398          use Exporter::Easy (
399              OK => [ qw(munge frobnicate) ],
400          );
401          # @ISA setup is automatic
402          # all assignments happen at compile time
403
404   What Not to Export
405       You have been warned already in "Selecting What to Export" to not
406       export:
407
408       ·   method names (because you don't need to and that's likely to not do
409           what you want),
410
411       ·   anything by default (because you don't want to surprise your
412           users...  badly)
413
414       ·   anything you don't need to (because less is more)
415
416       There's one more item to add to this list.  Do not export variable
417       names.  Just because "Exporter" lets you do that, it does not mean you
418       should.
419
420         @EXPORT_OK = qw($svar @avar %hvar); # DON'T!
421
422       Exporting variables is not a good idea.  They can change under the
423       hood, provoking horrible effects at-a-distance that are too hard to
424       track and to fix.  Trust me: they are not worth it.
425
426       To provide the capability to set/get class-wide settings, it is best
427       instead to provide accessors as subroutines or class methods instead.
428

SEE ALSO

430       "Exporter" is definitely not the only module with symbol exporter
431       capabilities.  At CPAN, you may find a bunch of them.  Some are
432       lighter.  Some provide improved APIs and features.  Pick the one that
433       fits your needs.  The following is a sample list of such modules.
434
435           Exporter::Easy
436           Exporter::Lite
437           Exporter::Renaming
438           Exporter::Tidy
439           Sub::Exporter / Sub::Installer
440           Perl6::Export / Perl6::Export::Attrs
441

LICENSE

443       This library is free software.  You can redistribute it and/or modify
444       it under the same terms as Perl itself.
445
446
447
448perl v5.26.3                      2019-05-11                       Exporter(3)
Impressum