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