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