1Exporter(3pm) Perl Programmers Reference Guide Exporter(3pm)
2
3
4
6 Exporter - Implements default import method for modules
7
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
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
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 list
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 Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.
135
136 An application using Module can say something like:
137
138 use Module qw(:DEFAULT :T2 !B3 A3);
139
140 Other examples include:
141
142 use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
143 use POSIX qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);
144
145 Remember that most patterns (using //) will need to be anchored with a
146 leading ^, e.g., "/^EXIT/" rather than "/EXIT/".
147
148 You can say "BEGIN { $Exporter::Verbose=1 }" to see how the
149 specifications are being processed and what is actually being imported
150 into modules.
151
152 Exporting without using Exporter's import method
153 Exporter has a special method, 'export_to_level' which is used in
154 situations where you can't directly call Exporter's import method. The
155 export_to_level method looks like:
156
157 MyPackage->export_to_level($where_to_export, $package, @what_to_export);
158
159 where $where_to_export is an integer telling how far up the calling
160 stack to export your symbols, and @what_to_export is an array telling
161 what symbols *to* export (usually this is @_). The $package argument
162 is currently unused.
163
164 For example, suppose that you have a module, A, which already has an
165 import function:
166
167 package A;
168
169 @ISA = qw(Exporter);
170 @EXPORT_OK = qw ($b);
171
172 sub import
173 {
174 $A::b = 1; # not a very useful import method
175 }
176
177 and you want to Export symbol $A::b back to the module that called
178 package A. Since Exporter relies on the import method to work, via
179 inheritance, as it stands Exporter::import() will never get called.
180 Instead, say the following:
181
182 package A;
183 @ISA = qw(Exporter);
184 @EXPORT_OK = qw ($b);
185
186 sub import
187 {
188 $A::b = 1;
189 A->export_to_level(1, @_);
190 }
191
192 This will export the symbols one level 'above' the current package -
193 ie: to the program or module that used package A.
194
195 Note: Be careful not to modify @_ at all before you call
196 export_to_level - or people using your package will get very
197 unexplained results!
198
199 Exporting without inheriting from Exporter
200 By including Exporter in your @ISA you inherit an Exporter's import()
201 method but you also inherit several other helper methods which you
202 probably don't want. To avoid this you can do
203
204 package YourModule;
205 use Exporter qw( import );
206
207 which will export Exporter's own import() method into YourModule.
208 Everything will work as before but you won't need to include Exporter
209 in @YourModule::ISA.
210
211 Note: This feature was introduced in version 5.57 of Exporter, released
212 with perl 5.8.3.
213
214 Module Version Checking
215 The Exporter module will convert an attempt to import a number from a
216 module into a call to "$module_name->require_version($value)". This can
217 be used to validate that the version of the module being used is
218 greater than or equal to the required version.
219
220 The Exporter module supplies a default "require_version" method which
221 checks the value of $VERSION in the exporting module.
222
223 Since the default "require_version" method treats the $VERSION number
224 as a simple numeric value it will regard version 1.10 as lower than
225 1.9. For this reason it is strongly recommended that you use numbers
226 with at least two decimal places, e.g., 1.09.
227
228 Managing Unknown Symbols
229 In some situations you may want to prevent certain symbols from being
230 exported. Typically this applies to extensions which have functions or
231 constants that may not exist on some systems.
232
233 The names of any symbols that cannot be exported should be listed in
234 the @EXPORT_FAIL array.
235
236 If a module attempts to import any of these symbols the Exporter will
237 give the module an opportunity to handle the situation before
238 generating an error. The Exporter will call an export_fail method with
239 a list of the failed symbols:
240
241 @failed_symbols = $module_name->export_fail(@failed_symbols);
242
243 If the "export_fail" method returns an empty list then no error is
244 recorded and all the requested symbols are exported. If the returned
245 list is not empty then an error is generated for each symbol and the
246 export fails. The Exporter provides a default "export_fail" method
247 which simply returns the list unchanged.
248
249 Uses for the "export_fail" method include giving better error messages
250 for some symbols and performing lazy architectural checks (put more
251 symbols into @EXPORT_FAIL by default and then take them out if someone
252 actually tries to use them and an expensive check shows that they are
253 usable on that platform).
254
255 Tag Handling Utility Functions
256 Since the symbols listed within %EXPORT_TAGS must also appear in either
257 @EXPORT or @EXPORT_OK, two utility functions are provided which allow
258 you to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK:
259
260 %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
261
262 Exporter::export_tags('foo'); # add aa, bb and cc to @EXPORT
263 Exporter::export_ok_tags('bar'); # add aa, cc and dd to @EXPORT_OK
264
265 Any names which are not tags are added to @EXPORT or @EXPORT_OK
266 unchanged but will trigger a warning (with "-w") to avoid misspelt tags
267 names being silently added to @EXPORT or @EXPORT_OK. Future versions
268 may make this a fatal error.
269
270 Generating combined tags
271 If several symbol categories exist in %EXPORT_TAGS, it's usually useful
272 to create the utility ":all" to simplify "use" statements.
273
274 The simplest way to do this is:
275
276 %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
277
278 # add all the other ":class" tags to the ":all" class,
279 # deleting duplicates
280 {
281 my %seen;
282
283 push @{$EXPORT_TAGS{all}},
284 grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;
285 }
286
287 CGI.pm creates an ":all" tag which contains some (but not really all)
288 of its categories. That could be done with one small change:
289
290 # add some of the other ":class" tags to the ":all" class,
291 # deleting duplicates
292 {
293 my %seen;
294
295 push @{$EXPORT_TAGS{all}},
296 grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}
297 foreach qw/html2 html3 netscape form cgi internal/;
298 }
299
300 Note that the tag names in %EXPORT_TAGS don't have the leading ':'.
301
302 "AUTOLOAD"ed Constants
303 Many modules make use of "AUTOLOAD"ing for constant subroutines to
304 avoid having to compile and waste memory on rarely used values (see
305 perlsub for details on constant subroutines). Calls to such constant
306 subroutines are not optimized away at compile time because they can't
307 be checked at compile time for constancy.
308
309 Even if a prototype is available at compile time, the body of the
310 subroutine is not (it hasn't been "AUTOLOAD"ed yet). perl needs to
311 examine both the "()" prototype and the body of a subroutine at compile
312 time to detect that it can safely replace calls to that subroutine with
313 the constant value.
314
315 A workaround for this is to call the constants once in a "BEGIN" block:
316
317 package My ;
318
319 use Socket ;
320
321 foo( SO_LINGER ); ## SO_LINGER NOT optimized away; called at runtime
322 BEGIN { SO_LINGER }
323 foo( SO_LINGER ); ## SO_LINGER optimized away at compile time.
324
325 This forces the "AUTOLOAD" for "SO_LINGER" to take place before
326 SO_LINGER is encountered later in "My" package.
327
328 If you are writing a package that "AUTOLOAD"s, consider forcing an
329 "AUTOLOAD" for any constants explicitly imported by other packages or
330 which are usually used when your package is "use"d.
331
333 Declaring @EXPORT_OK and Friends
334 When using "Exporter" with the standard "strict" and "warnings"
335 pragmas, the "our" keyword is needed to declare the package variables
336 @EXPORT_OK, @EXPORT, @ISA, etc.
337
338 our @ISA = qw(Exporter);
339 our @EXPORT_OK = qw(munge frobnicate);
340
341 If backward compatibility for Perls under 5.6 is important, one must
342 write instead a "use vars" statement.
343
344 use vars qw(@ISA @EXPORT_OK);
345 @ISA = qw(Exporter);
346 @EXPORT_OK = qw(munge frobnicate);
347
348 Playing Safe
349 There are some caveats with the use of runtime statements like "require
350 Exporter" and the assignment to package variables, which can very
351 subtle for the unaware programmer. This may happen for instance with
352 mutually recursive modules, which are affected by the time the relevant
353 constructions are executed.
354
355 The ideal (but a bit ugly) way to never have to think about that is to
356 use "BEGIN" blocks. So the first part of the "SYNOPSIS" code could be
357 rewritten as:
358
359 package YourModule;
360
361 use strict;
362 use warnings;
363
364 our (@ISA, @EXPORT_OK);
365 BEGIN {
366 require Exporter;
367 @ISA = qw(Exporter);
368 @EXPORT_OK = qw(munge frobnicate); # symbols to export on request
369 }
370
371 The "BEGIN" will assure that the loading of Exporter.pm and the
372 assignments to @ISA and @EXPORT_OK happen immediately, leaving no room
373 for something to get awry or just plain wrong.
374
375 With respect to loading "Exporter" and inheriting, there are
376 alternatives with the use of modules like "base" and "parent".
377
378 use base qw( Exporter );
379 # or
380 use parent qw( Exporter );
381
382 Any of these statements are nice replacements for "BEGIN { require
383 Exporter; @ISA = qw(Exporter); }" with the same compile-time effect.
384 The basic difference is that "base" code interacts with declared
385 "fields" while "parent" is a streamlined version of the older "base"
386 code to just establish the IS-A relationship.
387
388 For more details, see the documentation and code of base and parent.
389
390 Another thorough remedy to that runtime vs. compile-time trap is to
391 use Exporter::Easy, which is a wrapper of Exporter that allows all
392 boilerplate code at a single gulp in the use statement.
393
394 use Exporter::Easy (
395 OK => [ qw(munge frobnicate) ],
396 );
397 # @ISA setup is automatic
398 # all assignments happen at compile time
399
400 What not to Export
401 You have been warned already in "Selecting What To Export" to not
402 export:
403
404 · method names (because you don't need to and that's likely to not do
405 what you want),
406
407 · anything by default (because you don't want to surprise your
408 users... badly)
409
410 · anything you don't need to (because less is more)
411
412 There's one more item to add to this list. Do not export variable
413 names. Just because "Exporter" lets you do that, it does not mean you
414 should.
415
416 @EXPORT_OK = qw( $svar @avar %hvar ); # DON'T!
417
418 Exporting variables is not a good idea. They can change under the hood,
419 provoking horrible effects at-a-distance, that are too hard to track
420 and to fix. Trust me: they are not worth it.
421
422 To provide the capability to set/get class-wide settings, it is best
423 instead to provide accessors as subroutines or class methods instead.
424
426 "Exporter" is definitely not the only module with symbol exporter
427 capabilities. At CPAN, you may find a bunch of them. Some are lighter.
428 Some provide improved APIs and features. Peek the one that fits your
429 needs. The following is a sample list of such modules.
430
431 Exporter::Easy
432 Exporter::Lite
433 Exporter::Renaming
434 Exporter::Tidy
435 Sub::Exporter / Sub::Installer
436 Perl6::Export / Perl6::Export::Attrs
437
439 This library is free software. You can redistribute it and/or modify it
440 under the same terms as Perl itself.
441
442
443
444perl v5.12.4 2011-06-07 Exporter(3pm)