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