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