1Sub::Exporter(3) User Contributed Perl Documentation Sub::Exporter(3)
2
3
4
6 Sub::Exporter - a sophisticated exporter for custom-built routines
7
9 version 0.982
10
12 Sub::Exporter must be used in two places. First, in an exporting
13 module:
14
15 # in the exporting module:
16 package Text::Tweaker;
17 use Sub::Exporter -setup => {
18 exports => [
19 qw(squish titlecase), # always works the same way
20 reformat => \&build_reformatter, # generator to build exported function
21 trim => \&build_trimmer,
22 indent => \&build_indenter,
23 ],
24 collectors => [ 'defaults' ],
25 };
26
27 Then, in an importing module:
28
29 # in the importing module:
30 use Text::Tweaker
31 'squish',
32 indent => { margin => 5 },
33 reformat => { width => 79, justify => 'full', -as => 'prettify_text' },
34 defaults => { eol => 'CRLF' };
35
36 With this setup, the importing module ends up with three routines:
37 "squish", "indent", and "prettify_text". The latter two have been
38 built to the specifications of the importer -- they are not just copies
39 of the code in the exporting package.
40
42 ACHTUNG! If you're not familiar with Exporter or exporting, read
43 Sub::Exporter::Tutorial first!
44
45 Why Generators?
46 The biggest benefit of Sub::Exporter over existing exporters (including
47 the ubiquitous Exporter.pm) is its ability to build new coderefs for
48 export, rather than to simply export code identical to that found in
49 the exporting package.
50
51 If your module's consumers get a routine that works like this:
52
53 use Data::Analyze qw(analyze);
54 my $value = analyze($data, $tolerance, $passes);
55
56 and they constantly pass only one or two different set of values for
57 the non-$data arguments, your code can benefit from Sub::Exporter. By
58 writing a simple generator, you can let them do this, instead:
59
60 use Data::Analyze
61 analyze => { tolerance => 0.10, passes => 10, -as => analyze10 },
62 analyze => { tolerance => 0.15, passes => 50, -as => analyze50 };
63
64 my $value = analyze10($data);
65
66 The generator for that would look something like this:
67
68 sub build_analyzer {
69 my ($class, $name, $arg) = @_;
70
71 return sub {
72 my $data = shift;
73 my $tolerance = shift || $arg->{tolerance};
74 my $passes = shift || $arg->{passes};
75
76 analyze($data, $tolerance, $passes);
77 }
78 }
79
80 Your module's user now has to do less work to benefit from it -- and
81 remember, you're often your own user! Investing in customized
82 subroutines is an investment in future laziness.
83
84 This also avoids a common form of ugliness seen in many modules:
85 package-level configuration. That is, you might have seen something
86 like the above implemented like so:
87
88 use Data::Analyze qw(analyze);
89 $Data::Analyze::default_tolerance = 0.10;
90 $Data::Analyze::default_passes = 10;
91
92 This might save time, until you have multiple modules using
93 Data::Analyze. Because there is only one global configuration, they
94 step on each other's toes and your code begins to have mysterious
95 errors.
96
97 Generators can also allow you to export class methods to be called as
98 subroutines:
99
100 package Data::Methodical;
101 use Sub::Exporter -setup => { exports => { some_method => \&_curry_class } };
102
103 sub _curry_class {
104 my ($class, $name) = @_;
105 sub { $class->$name(@_); };
106 }
107
108 Because of the way that exporters and Sub::Exporter work, any package
109 that inherits from Data::Methodical can inherit its exporter and
110 override its "some_method". If a user imports "some_method" from that
111 package, he'll receive a subroutine that calls the method on the
112 subclass, rather than on Data::Methodical itself.
113
114 Other Customizations
115 Building custom routines with generators isn't the only way that
116 Sub::Exporters allows the importing code to refine its use of the
117 exported routines. They may also be renamed to avoid naming
118 collisions.
119
120 Consider the following code:
121
122 # this program determines to which circle of Hell you will be condemned
123 use Morality qw(sin virtue); # for calculating viciousness
124 use Math::Trig qw(:all); # for dealing with circles
125
126 The programmer has inadvertantly imported two "sin" routines. The
127 solution, in Exporter.pm-based modules, would be to import only one and
128 then call the other by its fully-qualified name. Alternately, the
129 importer could write a routine that did so, or could mess about with
130 typeglobs.
131
132 How much easier to write:
133
134 # this program determines to which circle of Hell you will be condemned
135 use Morality qw(virtue), sin => { -as => 'offense' };
136 use Math::Trig -all => { -prefix => 'trig_' };
137
138 and to have at one's disposal "offense" and "trig_sin" -- not to
139 mention "trig_cos" and "trig_tan".
140
142 You can configure an exporter for your package by using Sub::Exporter
143 like so:
144
145 package Tools;
146 use Sub::Exporter
147 -setup => { exports => [ qw(function1 function2 function3) ] };
148
149 This is the simplest way to use the exporter, and is basically
150 equivalent to this:
151
152 package Tools;
153 use base qw(Exporter);
154 our @EXPORT_OK = qw(function1 function2 function2);
155
156 Any basic use of Sub::Exporter will look like this:
157
158 package Tools;
159 use Sub::Exporter -setup => \%config;
160
161 The following keys are valid in %config:
162
163 exports - a list of routines to provide for exporting; each routine may be
164 followed by generator
165 groups - a list of groups to provide for exporting; each must be followed by
166 either (a) a list of exports, possibly with arguments for each
167 export, or (b) a generator
168
169 collectors - a list of names into which values are collected for use in
170 routine generation; each name may be followed by a validator
171
172 In addition to the basic options above, a few more advanced options may
173 be passed:
174
175 into_level - how far up the caller stack to look for a target (default 0)
176 into - an explicit target (package) into which to export routines
177
178 In other words: Sub::Exporter installs a "import" routine which, when
179 called, exports routines to the calling namespace. The "into" and
180 "into_level" options change where those exported routines are
181 installed.
182
183 generator - a callback used to produce the code that will be installed
184 default: Sub::Exporter::default_generator
185
186 installer - a callback used to install the code produced by the generator
187 default: Sub::Exporter::default_installer
188
189 For information on how these callbacks are used, see the documentation
190 for "default_generator" and "default_installer".
191
192 Export Configuration
193 The "exports" list may be provided as an array reference or a hash
194 reference. The list is processed in such a way that the following are
195 equivalent:
196
197 { exports => [ qw(foo bar baz), quux => \&quux_generator ] }
198
199 { exports =>
200 { foo => undef, bar => undef, baz => undef, quux => \&quux_generator } }
201
202 Generators are code that return coderefs. They are called with four
203 parameters:
204
205 $class - the class whose exporter has been called (the exporting class)
206 $name - the name of the export for which the routine is being build
207 \%arg - the arguments passed for this export
208 \%col - the collections for this import
209
210 Given the configuration in the "SYNOPSIS", the following "use"
211 statement:
212
213 use Text::Tweaker
214 reformat => { -as => 'make_narrow', width => 33 },
215 defaults => { eol => 'CR' };
216
217 would result in the following call to &build_reformatter:
218
219 my $code = build_reformatter(
220 'Text::Tweaker',
221 'reformat',
222 { width => 33 }, # note that -as is not passed in
223 { defaults => { eol => 'CR' } },
224 );
225
226 The returned coderef ($code) would then be installed as "make_narrow"
227 in the calling package.
228
229 Instead of providing a coderef in the configuration, a reference to a
230 method name may be provided. This method will then be called on the
231 invocant of the "import" method. (In this case, we do not pass the
232 $class parameter, as it would be redundant.)
233
234 Group Configuration
235 The "groups" list can be passed in the same forms as "exports". Groups
236 must have values to be meaningful, which may either list exports that
237 make up the group (optionally with arguments) or may provide a way to
238 build the group.
239
240 The simpler case is the first: a group definition is a list of exports.
241 Here's the example that could go in exporter in the "SYNOPSIS".
242
243 groups => {
244 default => [ qw(reformat) ],
245 shorteners => [ qw(squish trim) ],
246 email_safe => [
247 'indent',
248 reformat => { -as => 'email_format', width => 72 }
249 ],
250 },
251
252 Groups are imported by specifying their name prefixed be either a dash
253 or a colon. This line of code would import the "shorteners" group:
254
255 use Text::Tweaker qw(-shorteners);
256
257 Arguments passed to a group when importing are merged into the groups
258 options and passed to any relevant generators. Groups can contain
259 other groups, but looping group structures are ignored.
260
261 The other possible value for a group definition, a coderef, allows one
262 generator to build several exportable routines simultaneously. This is
263 useful when many routines must share enclosed lexical variables. The
264 coderef must return a hash reference. The keys will be used as export
265 names and the values are the subs that will be exported.
266
267 This example shows a simple use of the group generator.
268
269 package Data::Crypto;
270 use Sub::Exporter -setup => { groups => { cipher => \&build_cipher_group } };
271
272 sub build_cipher_group {
273 my ($class, $group, $arg) = @_;
274 my ($encode, $decode) = build_codec($arg->{secret});
275 return { cipher => $encode, decipher => $decode };
276 }
277
278 The "cipher" and "decipher" routines are built in a group because they
279 are built together by code which encloses their secret in their
280 environment.
281
282 Default Groups
283
284 If a module that uses Sub::Exporter is "use"d with no arguments, it
285 will try to export the group named "default". If that group has not
286 been specifically configured, it will be empty, and nothing will
287 happen.
288
289 Another group is also created if not defined: "all". The "all" group
290 contains all the exports from the exports list.
291
292 Collector Configuration
293 The "collectors" entry in the exporter configuration gives names which,
294 when found in the import call, have their values collected and passed
295 to every generator.
296
297 For example, the "build_analyzer" generator that we saw above could be
298 rewritten as:
299
300 sub build_analyzer {
301 my ($class, $name, $arg, $col) = @_;
302
303 return sub {
304 my $data = shift;
305 my $tolerance = shift || $arg->{tolerance} || $col->{defaults}{tolerance};
306 my $passes = shift || $arg->{passes} || $col->{defaults}{passes};
307
308 analyze($data, $tolerance, $passes);
309 }
310 }
311
312 That would allow the import to specify global defaults for his imports:
313
314 use Data::Analyze
315 'analyze',
316 analyze => { tolerance => 0.10, -as => analyze10 },
317 analyze => { tolerance => 0.15, passes => 50, -as => analyze50 },
318 defaults => { passes => 10 };
319
320 my $A = analyze10($data); # equivalent to analyze($data, 0.10, 10);
321 my $C = analyze50($data); # equivalent to analyze($data, 0.15, 10);
322 my $B = analyze($data, 0.20); # equivalent to analyze($data, 0.20, 10);
323
324 If values are provided in the "collectors" list during exporter setup,
325 they must be code references, and are used to validate the importer's
326 values. The validator is called when the collection is found, and if
327 it returns false, an exception is thrown. We could ensure that no one
328 tries to set a global data default easily:
329
330 collectors => { defaults => sub { return (exists $_[0]->{data}) ? 0 : 1 } }
331
332 Collector coderefs can also be used as hooks to perform arbitrary
333 actions before anything is exported.
334
335 When the coderef is called, it is passed the value of the collection
336 and a hashref containing the following entries:
337
338 name - the name of the collector
339 config - the exporter configuration (hashref)
340 import_args - the arguments passed to the exporter, sans collections (aref)
341 class - the package on which the importer was called
342 into - the package into which exports will be exported
343
344 Collectors with all-caps names (that is, made up of underscore or
345 capital A through Z) are reserved for special use. The only currently
346 implemented special collector is "INIT", whose hook (if present in the
347 exporter configuration) is always run before any other hook.
348
350 Arguments to the exporter (that is, the arguments after the module name
351 in a "use" statement) are parsed as follows:
352
353 First, the collectors gather any collections found in the arguments.
354 Any reference type may be given as the value for a collector. For each
355 collection given in the arguments, its validator (if any) is called.
356
357 Next, groups are expanded. If the group is implemented by a group
358 generator, the generator is called. There are two special arguments
359 which, if given to a group, have special meaning:
360
361 -prefix - a string to prepend to any export imported from this group
362 -suffix - a string to append to any export imported from this group
363
364 Finally, individual export generators are called and all subs,
365 generated or otherwise, are installed in the calling package. There is
366 only one special argument for export generators:
367
368 -as - where to install the exported sub
369
370 Normally, "-as" will contain an alternate name for the routine. It
371 may, however, contain a reference to a scalar. If that is the case, a
372 reference the generated routine will be placed in the scalar referenced
373 by "-as". It will not be installed into the calling package.
374
375 Special Exporter Arguments
376 The generated exporter accept some special options, which may be passed
377 as the first argument, in a hashref.
378
379 These options are:
380
381 into_level
382 into
383 generator
384 installer
385
386 These override the same-named configuration options described in
387 "EXPORTER CONFIGURATION".
388
390 setup_exporter
391 This routine builds and installs an "import" routine. It is called
392 with one argument, a hashref containing the exporter configuration.
393 Using this, it builds an exporter and installs it into the calling
394 package with the name "import." In addition to the normal exporter
395 configuration, a few named arguments may be passed in the hashref:
396
397 into - into what package should the exporter be installed
398 into_level - into what level up the stack should the exporter be installed
399 as - what name should the installed exporter be given
400
401 By default the exporter is installed with the name "import" into the
402 immediate caller of "setup_exporter". In other words, if your package
403 calls "setup_exporter" without providing any of the three above
404 arguments, it will have an "import" routine installed.
405
406 Providing both "into" and "into_level" will cause an exception to be
407 thrown.
408
409 The exporter is built by "build_exporter".
410
411 build_exporter
412 Given a standard exporter configuration, this routine builds and
413 returns an exporter -- that is, a subroutine that can be installed as a
414 class method to perform exporting on request.
415
416 Usually, this method is called by "setup_exporter", which then installs
417 the exporter as a package's import routine.
418
419 default_generator
420 This is Sub::Exporter's default generator. It takes bits of
421 configuration that have been gathered during the import and turns them
422 into a coderef that can be installed.
423
424 my $code = default_generator(\%arg);
425
426 Passed arguments are:
427
428 class - the class on which the import method was called
429 name - the name of the export being generated
430 arg - the arguments to the generator
431 col - the collections
432
433 generator - the generator to be used to build the export (code or scalar ref)
434
435 default_installer
436 This is Sub::Exporter's default installer. It does what Sub::Exporter
437 promises: it installs code into the target package.
438
439 default_installer(\%arg, \@to_export);
440
441 Passed arguments are:
442
443 into - the package into which exports should be delivered
444
445 @to_export is a list of name/value pairs. The default exporter assigns
446 code (the values) to named slots (the names) in the given package. If
447 the name is a scalar reference, the scalar reference is made to point
448 to the code reference instead.
449
451 Sub::Exporter also offers its own exports: the "setup_exporter" and
452 "build_exporter" routines described above. It also provides a special
453 "setup" collector, which will set up an exporter using the parameters
454 passed to it.
455
456 Note that the "setup" collector (seen in examples like the "SYNOPSIS"
457 above) uses "build_exporter", not "setup_exporter". This means that
458 the special arguments like "into" and "as" for "setup_exporter" are not
459 accepted here. Instead, you may write something like:
460
461 use Sub::Exporter
462 { into => 'Target::Package' },
463 -setup => {
464 -as => 'do_import',
465 exports => [ ... ],
466 }
467 ;
468
469 Finding a good reason for wanting to do this is left as as exercise for
470 the reader.
471
473 There are a whole mess of exporters on the CPAN. The features included
474 in Sub::Exporter set it apart from any existing Exporter. Here's a
475 summary of some other exporters and how they compare.
476
477 · Exporter and co.
478
479 This is the standard Perl exporter. Its interface is a little
480 clunky, but it's fast and ubiquitous. It can do some things that
481 Sub::Exporter can't: it can export things other than routines, it
482 can import "everything in this group except this symbol," and some
483 other more esoteric things. These features seem to go nearly
484 entirely unused.
485
486 It always exports things exactly as they appear in the exporting
487 module; it can't rename or customize routines. Its groups ("tags")
488 can't be nested.
489
490 Exporter::Lite is a whole lot like Exporter, but it does
491 significantly less: it supports exporting symbols, but not groups,
492 pattern matching, or negation.
493
494 The fact that Sub::Exporter can't export symbols other than
495 subroutines is a good idea, not a missing feature.
496
497 For simple uses, setting up Sub::Exporter is about as easy as
498 Exporter. For complex uses, Sub::Exporter makes hard things
499 possible, which would not be possible with Exporter.
500
501 When using a module that uses Sub::Exporter, users familiar with
502 Exporter will probably see no difference in the basics. These two
503 lines do about the same thing in whether the exporting module uses
504 Exporter or Sub::Exporter.
505
506 use Some::Module qw(foo bar baz);
507 use Some::Module qw(foo :bar baz);
508
509 The definition for exporting in Exporter.pm might look like this:
510
511 package Some::Module;
512 use base qw(Exporter);
513 our @EXPORT_OK = qw(foo bar baz quux);
514 our %EXPORT_TAGS = (bar => [ qw(bar baz) ]);
515
516 Using Sub::Exporter, it would look like this:
517
518 package Some::Module;
519 use Sub::Exporter -setup => {
520 exports => [ qw(foo bar baz quux) ],
521 groups => { bar => [ qw(bar baz) ]}
522 };
523
524 Sub::Exporter respects inheritance, so that a package may export
525 inherited routines, and will export the most inherited version.
526 Exporting methods without currying away the invocant is a bad idea,
527 but Sub::Exporter allows you to do just that -- and anyway, there
528 are other uses for this feature, like packages of exported
529 subroutines which use inheritance specifically to allow more
530 specialized, but similar, packages.
531
532 Exporter::Easy provides a wrapper around the standard Exporter. It
533 makes it simpler to build groups, but doesn't provide any more
534 functionality. Because it is a front-end to Exporter, it will
535 store your exporter's configuration in global package variables.
536
537 · Attribute-Based Exporters
538
539 Some exporters use attributes to mark variables to export.
540 Exporter::Simple supports exporting any kind of symbol, and
541 supports groups. Using a module like Exporter or Sub::Exporter,
542 it's easy to look at one place and see what is exported, but it's
543 impossible to look at a variable definition and see whether it is
544 exported by that alone. Exporter::Simple makes this trade in
545 reverse: each variable's declaration includes its export
546 definition, but there is no one place to look to find a manifest of
547 exports.
548
549 More importantly, Exporter::Simple does not add any new features to
550 those of Exporter. In fact, like Exporter::Easy, it is just a
551 front-end to Exporter, so it ends up storing its configuration in
552 global package variables. (This means that there is one place to
553 look for your exporter's manifest, actually. You can inspect the
554 @EXPORT package variables, and other related package variables, at
555 runtime.)
556
557 Perl6::Export isn't actually attribute based, but looks similar.
558 Its syntax is borrowed from Perl 6, and implemented by a source
559 filter. It is a prototype of an interface that is still being
560 designed. It should probably be avoided for production work. On
561 the other hand, Perl6::Export::Attrs implements Perl 6-like
562 exporting, but translates it into Perl 5 by providing attributes.
563
564 · Other Exporters
565
566 Exporter::Renaming wraps the standard Exporter to allow it to
567 export symbols with changed names.
568
569 Class::Exporter performs a special kind of routine generation,
570 giving each importing package an instance of your class, and then
571 exporting the instance's methods as normal routines.
572 (Sub::Exporter, of course, can easily emulate this behavior, as
573 shown above.)
574
575 Exporter::Tidy implements a form of renaming (using its "_map"
576 argument) and of prefixing, and implements groups. It also avoids
577 using package variables for its configuration.
578
580 · write a set of longer, more demonstrative examples
581
582 · solidify the "custom exporter" interface (see &default_exporter)
583
584 · add an "always" group
585
587 Ricardo SIGNES, "<rjbs@cpan.org>"
588
590 Hans Dieter Pearcey provided helpful advice while I was writing
591 Sub::Exporter. Ian Langworth and Shawn Sorichetti asked some good
592 questions and hepled me improve my documentation quite a bit. Yuval
593 Kogman helped me find a bunch of little problems.
594
595 Thanks, guys!
596
598 Please report any bugs or feature requests through the web interface at
599 <http://rt.cpan.org>. I will be notified, and then you'll automatically
600 be notified of progress on your bug as I make changes.
601
603 Copyright 2006-2007, Ricardo SIGNES. This program is free software;
604 you can redistribute it and/or modify it under the same terms as Perl
605 itself.
606
607
608
609perl v5.10.1 2009-01-16 Sub::Exporter(3)