File Coverage

blib/lib/Sub/Exporter.pm
Criterion Covered Total %
statement 174 181 96.1
branch 92 98 93.8
condition 51 55 92.7
subroutine 24 25 96.0
pod 4 5 80.0
total 345 364 94.7


line stmt bran cond sub pod time code
1 16     16   1976881 use v5.12.0;
  16         64  
2 16     16   134 use warnings;
  16         31  
  16         1542  
3             package Sub::Exporter 0.991;
4             # ABSTRACT: a sophisticated exporter for custom-built routines
5              
6 16     16   110 use Carp ();
  16         57  
  16         509  
7 16     16   7116 use Data::OptList 0.100 ();
  16         181474  
  16         643  
8 16     16   130 use Params::Util 0.14 (); # _CODELIKE
  16         312  
  16         456  
9 16     16   86 use Sub::Install 0.92 ();
  16         193  
  16         32514  
10              
11             #pod =head1 SYNOPSIS
12             #pod
13             #pod Sub::Exporter must be used in two places. First, in an exporting module:
14             #pod
15             #pod # in the exporting module:
16             #pod package Text::Tweaker;
17             #pod use Sub::Exporter -setup => {
18             #pod exports => [
19             #pod qw(squish titlecase), # always works the same way
20             #pod reformat => \&build_reformatter, # generator to build exported function
21             #pod trim => \&build_trimmer,
22             #pod indent => \&build_indenter,
23             #pod ],
24             #pod collectors => [ 'defaults' ],
25             #pod };
26             #pod
27             #pod Then, in an importing module:
28             #pod
29             #pod # in the importing module:
30             #pod use Text::Tweaker
31             #pod 'squish',
32             #pod indent => { margin => 5 },
33             #pod reformat => { width => 79, justify => 'full', -as => 'prettify_text' },
34             #pod defaults => { eol => 'CRLF' };
35             #pod
36             #pod With this setup, the importing module ends up with three routines: C,
37             #pod C, and C. The latter two have been built to the
38             #pod specifications of the importer -- they are not just copies of the code in the
39             #pod exporting package.
40             #pod
41             #pod =head1 DESCRIPTION
42             #pod
43             #pod B If you're not familiar with Exporter or exporting, read
44             #pod L first!
45             #pod
46             #pod =head2 Why Generators?
47             #pod
48             #pod The biggest benefit of Sub::Exporter over existing exporters (including the
49             #pod ubiquitous Exporter.pm) is its ability to build new coderefs for export, rather
50             #pod than to simply export code identical to that found in the exporting package.
51             #pod
52             #pod If your module's consumers get a routine that works like this:
53             #pod
54             #pod use Data::Analyze qw(analyze);
55             #pod my $value = analyze($data, $tolerance, $passes);
56             #pod
57             #pod and they constantly pass only one or two different set of values for the
58             #pod non-C<$data> arguments, your code can benefit from Sub::Exporter. By writing a
59             #pod simple generator, you can let them do this, instead:
60             #pod
61             #pod use Data::Analyze
62             #pod analyze => { tolerance => 0.10, passes => 10, -as => analyze10 },
63             #pod analyze => { tolerance => 0.15, passes => 50, -as => analyze50 };
64             #pod
65             #pod my $value = analyze10($data);
66             #pod
67             #pod The package with the generator for that would look something like this:
68             #pod
69             #pod package Data::Analyze;
70             #pod use Sub::Exporter -setup => {
71             #pod exports => [
72             #pod analyze => \&build_analyzer,
73             #pod ],
74             #pod };
75             #pod
76             #pod sub build_analyzer {
77             #pod my ($class, $name, $arg) = @_;
78             #pod
79             #pod return sub {
80             #pod my $data = shift;
81             #pod my $tolerance = shift || $arg->{tolerance};
82             #pod my $passes = shift || $arg->{passes};
83             #pod
84             #pod analyze($data, $tolerance, $passes);
85             #pod }
86             #pod }
87             #pod
88             #pod Your module's user now has to do less work to benefit from it -- and remember,
89             #pod you're often your own user! Investing in customized subroutines is an
90             #pod investment in future laziness.
91             #pod
92             #pod This also avoids a common form of ugliness seen in many modules: package-level
93             #pod configuration. That is, you might have seen something like the above
94             #pod implemented like so:
95             #pod
96             #pod use Data::Analyze qw(analyze);
97             #pod $Data::Analyze::default_tolerance = 0.10;
98             #pod $Data::Analyze::default_passes = 10;
99             #pod
100             #pod This might save time, until you have multiple modules using Data::Analyze.
101             #pod Because there is only one global configuration, they step on each other's toes
102             #pod and your code begins to have mysterious errors.
103             #pod
104             #pod Generators can also allow you to export class methods to be called as
105             #pod subroutines:
106             #pod
107             #pod package Data::Methodical;
108             #pod use Sub::Exporter -setup => { exports => { some_method => \&_curry_class } };
109             #pod
110             #pod sub _curry_class {
111             #pod my ($class, $name) = @_;
112             #pod sub { $class->$name(@_); };
113             #pod }
114             #pod
115             #pod Because of the way that exporters and Sub::Exporter work, any package that
116             #pod inherits from Data::Methodical can inherit its exporter and override its
117             #pod C. If a user imports C from that package, he'll
118             #pod receive a subroutine that calls the method on the subclass, rather than on
119             #pod Data::Methodical itself. Keep in mind that if you re-setup Sub::Exporter in a
120             #pod package that inherits from Data::Methodical you will, of course, be entirely
121             #pod replacing the exporter from Data::Methodical. C is a method, and is
122             #pod hidden by the same means as any other method.
123             #pod
124             #pod =head2 Other Customizations
125             #pod
126             #pod Building custom routines with generators isn't the only way that Sub::Exporters
127             #pod allows the importing code to refine its use of the exported routines. They may
128             #pod also be renamed to avoid naming collisions.
129             #pod
130             #pod Consider the following code:
131             #pod
132             #pod # this program determines to which circle of Hell you will be condemned
133             #pod use Morality qw(sin virtue); # for calculating viciousness
134             #pod use Math::Trig qw(:all); # for dealing with circles
135             #pod
136             #pod The programmer has inadvertently imported two C routines. The solution,
137             #pod in Exporter.pm-based modules, would be to import only one and then call the
138             #pod other by its fully-qualified name. Alternately, the importer could write a
139             #pod routine that did so, or could mess about with typeglobs.
140             #pod
141             #pod How much easier to write:
142             #pod
143             #pod # this program determines to which circle of Hell you will be condemned
144             #pod use Morality qw(virtue), sin => { -as => 'offense' };
145             #pod use Math::Trig -all => { -prefix => 'trig_' };
146             #pod
147             #pod and to have at one's disposal C and C -- not to mention
148             #pod C and C.
149             #pod
150             #pod =head1 EXPORTER CONFIGURATION
151             #pod
152             #pod You can configure an exporter for your package by using Sub::Exporter like so:
153             #pod
154             #pod package Tools;
155             #pod use Sub::Exporter
156             #pod -setup => { exports => [ qw(function1 function2 function3) ] };
157             #pod
158             #pod This is the simplest way to use the exporter, and is basically equivalent to
159             #pod this:
160             #pod
161             #pod package Tools;
162             #pod use base qw(Exporter);
163             #pod our @EXPORT_OK = qw(function1 function2 function3);
164             #pod
165             #pod Any basic use of Sub::Exporter will look like this:
166             #pod
167             #pod package Tools;
168             #pod use Sub::Exporter -setup => \%config;
169             #pod
170             #pod The following keys are valid in C<%config>:
171             #pod
172             #pod exports - a list of routines to provide for exporting; each routine may be
173             #pod followed by generator
174             #pod groups - a list of groups to provide for exporting; each must be followed by
175             #pod either (a) a list of exports, possibly with arguments for each
176             #pod export, or (b) a generator
177             #pod
178             #pod collectors - a list of names into which values are collected for use in
179             #pod routine generation; each name may be followed by a validator
180             #pod
181             #pod In addition to the basic options above, a few more advanced options may be
182             #pod passed:
183             #pod
184             #pod into_level - how far up the caller stack to look for a target (default 0)
185             #pod into - an explicit target (package) into which to export routines
186             #pod
187             #pod In other words: Sub::Exporter installs a C routine which, when called,
188             #pod exports routines to the calling namespace. The C and C
189             #pod options change where those exported routines are installed.
190             #pod
191             #pod generator - a callback used to produce the code that will be installed
192             #pod default: Sub::Exporter::default_generator
193             #pod
194             #pod installer - a callback used to install the code produced by the generator
195             #pod default: Sub::Exporter::default_installer
196             #pod
197             #pod For information on how these callbacks are used, see the documentation for
198             #pod C> and C>.
199             #pod
200             #pod =head2 Export Configuration
201             #pod
202             #pod The C list may be provided as an array reference or a hash reference.
203             #pod The list is processed in such a way that the following are equivalent:
204             #pod
205             #pod { exports => [ qw(foo bar baz), quux => \&quux_generator ] }
206             #pod
207             #pod { exports =>
208             #pod { foo => undef, bar => undef, baz => undef, quux => \&quux_generator } }
209             #pod
210             #pod Generators are code that return coderefs. They are called with four
211             #pod parameters:
212             #pod
213             #pod $class - the class whose exporter has been called (the exporting class)
214             #pod $name - the name of the export for which the routine is being build
215             #pod \%arg - the arguments passed for this export
216             #pod \%col - the collections for this import
217             #pod
218             #pod Given the configuration in the L, the following C statement:
219             #pod
220             #pod use Text::Tweaker
221             #pod reformat => { -as => 'make_narrow', width => 33 },
222             #pod defaults => { eol => 'CR' };
223             #pod
224             #pod would result in the following call to C<&build_reformatter>:
225             #pod
226             #pod my $code = build_reformatter(
227             #pod 'Text::Tweaker',
228             #pod 'reformat',
229             #pod { width => 33 }, # note that -as is not passed in
230             #pod { defaults => { eol => 'CR' } },
231             #pod );
232             #pod
233             #pod The returned coderef (C<$code>) would then be installed as C in the
234             #pod calling package.
235             #pod
236             #pod Instead of providing a coderef in the configuration, a reference to a method
237             #pod name may be provided. This method will then be called on the invocant of the
238             #pod C method. (In this case, we do not pass the C<$class> parameter, as it
239             #pod would be redundant.)
240             #pod
241             #pod =head2 Group Configuration
242             #pod
243             #pod The C list can be passed in the same forms as C. Groups must
244             #pod have values to be meaningful, which may either list exports that make up the
245             #pod group (optionally with arguments) or may provide a way to build the group.
246             #pod
247             #pod The simpler case is the first: a group definition is a list of exports. Here's
248             #pod the example that could go in exporter in the L.
249             #pod
250             #pod groups => {
251             #pod default => [ qw(reformat) ],
252             #pod shorteners => [ qw(squish trim) ],
253             #pod email_safe => [
254             #pod 'indent',
255             #pod reformat => { -as => 'email_format', width => 72 }
256             #pod ],
257             #pod },
258             #pod
259             #pod Groups are imported by specifying their name prefixed be either a dash or a
260             #pod colon. This line of code would import the C group:
261             #pod
262             #pod use Text::Tweaker qw(-shorteners);
263             #pod
264             #pod Arguments passed to a group when importing are merged into the groups options
265             #pod and passed to any relevant generators. Groups can contain other groups, but
266             #pod looping group structures are ignored.
267             #pod
268             #pod The other possible value for a group definition, a coderef, allows one
269             #pod generator to build several exportable routines simultaneously. This is useful
270             #pod when many routines must share enclosed lexical variables. The coderef must
271             #pod return a hash reference. The keys will be used as export names and the values
272             #pod are the subs that will be exported.
273             #pod
274             #pod This example shows a simple use of the group generator.
275             #pod
276             #pod package Data::Crypto;
277             #pod use Sub::Exporter -setup => { groups => { cipher => \&build_cipher_group } };
278             #pod
279             #pod sub build_cipher_group {
280             #pod my ($class, $group, $arg) = @_;
281             #pod my ($encode, $decode) = build_codec($arg->{secret});
282             #pod return { cipher => $encode, decipher => $decode };
283             #pod }
284             #pod
285             #pod The C and C routines are built in a group because they are
286             #pod built together by code which encloses their secret in their environment.
287             #pod
288             #pod =head3 Default Groups
289             #pod
290             #pod If a module that uses Sub::Exporter is Cd with no arguments, it will try
291             #pod to export the group named C. If that group has not been specifically
292             #pod configured, it will be empty, and nothing will happen.
293             #pod
294             #pod Another group is also created if not defined: C. The C group
295             #pod contains all the exports from the exports list.
296             #pod
297             #pod =head2 Collector Configuration
298             #pod
299             #pod The C entry in the exporter configuration gives names which, when
300             #pod found in the import call, have their values collected and passed to every
301             #pod generator.
302             #pod
303             #pod For example, the C generator that we saw above could be
304             #pod rewritten as:
305             #pod
306             #pod sub build_analyzer {
307             #pod my ($class, $name, $arg, $col) = @_;
308             #pod
309             #pod return sub {
310             #pod my $data = shift;
311             #pod my $tolerance = shift || $arg->{tolerance} || $col->{defaults}{tolerance};
312             #pod my $passes = shift || $arg->{passes} || $col->{defaults}{passes};
313             #pod
314             #pod analyze($data, $tolerance, $passes);
315             #pod }
316             #pod }
317             #pod
318             #pod That would allow the importer to specify global defaults for his imports:
319             #pod
320             #pod use Data::Analyze
321             #pod 'analyze',
322             #pod analyze => { tolerance => 0.10, -as => analyze10 },
323             #pod analyze => { tolerance => 0.15, passes => 50, -as => analyze50 },
324             #pod defaults => { passes => 10 };
325             #pod
326             #pod my $A = analyze10($data); # equivalent to analyze($data, 0.10, 10);
327             #pod my $C = analyze50($data); # equivalent to analyze($data, 0.15, 50);
328             #pod my $B = analyze($data, 0.20); # equivalent to analyze($data, 0.20, 10);
329             #pod
330             #pod If values are provided in the C list during exporter setup, they
331             #pod must be code references, and are used to validate the importer's values. The
332             #pod validator is called when the collection is found, and if it returns false, an
333             #pod exception is thrown. We could ensure that no one tries to set a global data
334             #pod default easily:
335             #pod
336             #pod collectors => { defaults => sub { return (exists $_[0]->{data}) ? 0 : 1 } }
337             #pod
338             #pod Collector coderefs can also be used as hooks to perform arbitrary actions
339             #pod before anything is exported.
340             #pod
341             #pod When the coderef is called, it is passed the value of the collection and a
342             #pod hashref containing the following entries:
343             #pod
344             #pod name - the name of the collector
345             #pod config - the exporter configuration (hashref)
346             #pod import_args - the arguments passed to the exporter, sans collections (aref)
347             #pod class - the package on which the importer was called
348             #pod into - the package into which exports will be exported
349             #pod
350             #pod Collectors with all-caps names (that is, made up of underscore or capital A
351             #pod through Z) are reserved for special use. The only currently implemented
352             #pod special collector is C, whose hook (if present in the exporter
353             #pod configuration) is always run before any other hook.
354             #pod
355             #pod =head1 CALLING THE EXPORTER
356             #pod
357             #pod Arguments to the exporter (that is, the arguments after the module name in a
358             #pod C statement) are parsed as follows:
359             #pod
360             #pod First, the collectors gather any collections found in the arguments. Any
361             #pod reference type may be given as the value for a collector. For each collection
362             #pod given in the arguments, its validator (if any) is called.
363             #pod
364             #pod Next, groups are expanded. If the group is implemented by a group generator,
365             #pod the generator is called. There are two special arguments which, if given to a
366             #pod group, have special meaning:
367             #pod
368             #pod -prefix - a string to prepend to any export imported from this group
369             #pod -suffix - a string to append to any export imported from this group
370             #pod
371             #pod Finally, individual export generators are called and all subs, generated or
372             #pod otherwise, are installed in the calling package. There is only one special
373             #pod argument for export generators:
374             #pod
375             #pod -as - where to install the exported sub
376             #pod
377             #pod Normally, C<-as> will contain an alternate name for the routine. It may,
378             #pod however, contain a reference to a scalar. If that is the case, a reference the
379             #pod generated routine will be placed in the scalar referenced by C<-as>. It will
380             #pod not be installed into the calling package.
381             #pod
382             #pod =head2 Special Exporter Arguments
383             #pod
384             #pod The generated exporter accept some special options, which may be passed as the
385             #pod first argument, in a hashref.
386             #pod
387             #pod These options are:
388             #pod
389             #pod into_level
390             #pod into
391             #pod generator
392             #pod installer
393             #pod
394             #pod These override the same-named configuration options described in L
395             #pod CONFIGURATION>.
396             #pod
397             #pod =cut
398              
399             # Given a potential import name, this returns the group name -- if it's got a
400             # group prefix.
401             sub _group_name {
402 508     508   1129 my ($name) = @_;
403              
404 508 100       1777 return if (index q{-:}, (substr $name, 0, 1)) == -1;
405 286         961 return substr $name, 1;
406             }
407              
408             # \@groups is a canonicalized opt list of exports and groups this returns
409             # another canonicalized opt list with groups replaced with relevant exports.
410             # \%seen is groups we've already expanded and can ignore.
411             # \%merge is merged options from the group we're descending through.
412             sub _expand_groups {
413 284     284   52709 my ($class, $config, $groups, $collection, $seen, $merge) = @_;
414 284   100     1108 $seen ||= {};
415 284   100     962 $merge ||= {};
416 284         696 my @groups = @$groups;
417              
418 284         865 for my $i (reverse 0 .. $#groups) {
419 351 100       915 if (my $group_name = _group_name($groups[$i][0])) {
420 129         942 my $seen = { %$seen }; # faux-dynamic scoping
421              
422 129         437 splice @groups, $i, 1,
423             _expand_group($class, $config, $groups[$i], $collection, $seen, $merge);
424             } else {
425             # there's nothing to munge in this export's args
426 222 100       1834 next unless my %merge = %$merge;
427              
428             # we have things to merge in; do so
429 72   100     236 my $prefix = (delete $merge{-prefix}) || '';
430 72   100     216 my $suffix = (delete $merge{-suffix}) || '';
431              
432 72 100 66     972 if (
433             Params::Util::_CODELIKE($groups[$i][1]) ## no critic Private
434             or
435             Params::Util::_SCALAR0($groups[$i][1]) ## no critic Private
436             ) {
437             # this entry was build by a group generator
438 14         52 $groups[$i][0] = $prefix . $groups[$i][0] . $suffix;
439             } else {
440             my $as
441             = ref $groups[$i][1]{-as} ? $groups[$i][1]{-as}
442 58 100       287 : $groups[$i][1]{-as} ? $prefix . $groups[$i][1]{-as} . $suffix
    100          
443             : $prefix . $groups[$i][0] . $suffix;
444              
445 58         89 $groups[$i][1] = { %{ $groups[$i][1] }, %merge, -as => $as };
  58         382  
446             }
447             }
448             }
449              
450 282         1608 return \@groups;
451             }
452              
453             # \@group is a name/value pair from an opt list.
454             sub _expand_group {
455 157     157   963088 my ($class, $config, $group, $collection, $seen, $merge) = @_;
456 157   100     481 $merge ||= {};
457              
458 157         362 my ($group_name, $group_arg) = @$group;
459 157         342 $group_name = _group_name($group_name);
460              
461             Carp::croak qq(group "$group_name" is not exported by the $class module)
462 157 100       695 unless exists $config->{groups}{$group_name};
463              
464 156 100       591 return if $seen->{$group_name}++;
465              
466 150 100       342 if (ref $group_arg) {
467 73   100     376 my $prefix = (delete $merge->{-prefix}||'') . ($group_arg->{-prefix}||'');
      100        
468 73   100     386 my $suffix = ($group_arg->{-suffix}||'') . (delete $merge->{-suffix}||'');
      100        
469 73 100       476 $merge = {
    100          
470             %$merge,
471             %$group_arg,
472             ($prefix ? (-prefix => $prefix) : ()),
473             ($suffix ? (-suffix => $suffix) : ()),
474             };
475             }
476              
477 150         393 my $exports = $config->{groups}{$group_name};
478              
479 150 100 100     866 if (
480             Params::Util::_CODELIKE($exports) ## no critic Private
481             or
482             Params::Util::_SCALAR0($exports) ## no critic Private
483             ) {
484             # I'm not very happy with this code for hiding -prefix and -suffix, but
485             # it's needed, and I'm not sure, offhand, how to make it better.
486             # -- rjbs, 2006-12-05
487 14 50       109 my $group_arg = $merge ? { %$merge } : {};
488 14         78 delete $group_arg->{-prefix};
489 14         26 delete $group_arg->{-suffix};
490              
491 14 100       61 my $group = Params::Util::_CODELIKE($exports) ## no critic Private
492             ? $exports->($class, $group_name, $group_arg, $collection)
493             : $class->$$exports($group_name, $group_arg, $collection);
494              
495 14 100       435 Carp::croak qq(group generator "$group_name" did not return a hashref)
496             if ref $group ne 'HASH';
497              
498 13         39 my $stuff = [ map { [ $_ => $group->{$_} ] } keys %$group ];
  24         1210  
499             return @{
500 13         23 _expand_groups($class, $config, $stuff, $collection, $seen, $merge)
  13         36  
501             };
502             } else {
503 136         618 $exports
504             = Data::OptList::mkopt($exports, "$group_name exports");
505              
506             return @{
507 136         6324 _expand_groups($class, $config, $exports, $collection, $seen, $merge)
  136         517  
508             };
509             }
510             }
511              
512             sub _mk_collection_builder {
513 113     113   242 my ($col, $etc) = @_;
514 113         342 my ($config, $import_args, $class, $into) = @$etc;
515              
516 113         189 my %seen;
517             sub {
518 37     37   70 my ($collection) = @_;
519 37         84 my ($name, $value) = @$collection;
520              
521             Carp::croak "collection $name provided multiple times in import"
522 37 100       316 if $seen{ $name }++;
523              
524 36 100       130 if (ref(my $hook = $config->{collectors}{$name})) {
525 30         177 my $arg = {
526             name => $name,
527             config => $config,
528             import_args => $import_args,
529             class => $class,
530             into => $into,
531             };
532              
533 30         97 my $error_msg = "collection $name failed validation";
534 30 100       1067 if (Params::Util::_SCALAR0($hook)) { ## no critic Private
535 2 100       13 Carp::croak $error_msg unless $class->$$hook($value, $arg);
536             } else {
537 28 100       92 Carp::croak $error_msg unless $hook->($value, $arg);
538             }
539             }
540              
541 30         135 $col->{ $name } = $value;
542             }
543 113         688 }
544              
545             # Given a config and pre-canonicalized importer args, remove collections from
546             # the args and return them.
547             sub _collect_collections {
548 113     113   900986 my ($config, $import_args, $class, $into) = @_;
549              
550             my @collections
551 35         127 = map { splice @$import_args, $_, 1 }
552 113         388 grep { exists $config->{collectors}{ $import_args->[$_][0] } }
  131         518  
553             reverse 0 .. $#$import_args;
554              
555 113 100       348 unshift @collections, [ INIT => {} ] if $config->{collectors}{INIT};
556              
557 113         188 my $col = {};
558 113         343 my $builder = _mk_collection_builder($col, \@_);
559 113         354 for my $collection (@collections) {
560 37         85 $builder->($collection)
561             }
562              
563 106         1057 return $col;
564             }
565              
566             #pod =head1 SUBROUTINES
567             #pod
568             #pod =head2 setup_exporter
569             #pod
570             #pod This routine builds and installs an C routine. It is called with one
571             #pod argument, a hashref containing the exporter configuration. Using this, it
572             #pod builds an exporter and installs it into the calling package with the name
573             #pod "import." In addition to the normal exporter configuration, a few named
574             #pod arguments may be passed in the hashref:
575             #pod
576             #pod into - into what package should the exporter be installed
577             #pod into_level - into what level up the stack should the exporter be installed
578             #pod as - what name should the installed exporter be given
579             #pod
580             #pod By default the exporter is installed with the name C into the immediate
581             #pod caller of C. In other words, if your package calls
582             #pod C without providing any of the three above arguments, it will
583             #pod have an C routine installed.
584             #pod
585             #pod Providing both C and C will cause an exception to be thrown.
586             #pod
587             #pod The exporter is built by C>.
588             #pod
589             #pod =cut
590              
591             sub setup_exporter {
592 23     23 1 3555 my ($config) = @_;
593              
594             Carp::croak 'into and into_level may not both be supplied to exporter'
595 23 100 100     244 if exists $config->{into} and exists $config->{into_level};
596              
597 22   100     157 my $as = delete $config->{as} || 'import';
598             my $into
599             = exists $config->{into} ? delete $config->{into}
600             : exists $config->{into_level} ? caller(delete $config->{into_level})
601 22 100       133 : caller(0);
    100          
602              
603 22         76 my $import = build_exporter($config);
604              
605 22         160 Sub::Install::reinstall_sub({
606             code => $import,
607             into => $into,
608             as => $as,
609             });
610             }
611              
612             #pod =head2 build_exporter
613             #pod
614             #pod Given a standard exporter configuration, this routine builds and returns an
615             #pod exporter -- that is, a subroutine that can be installed as a class method to
616             #pod perform exporting on request.
617             #pod
618             #pod Usually, this method is called by C>, which then installs
619             #pod the exporter as a package's import routine.
620             #pod
621             #pod =cut
622              
623             sub _key_intersection {
624 51     51   139 my ($x, $y) = @_;
625 51         188 my %seen = map { $_ => 1 } keys %$x;
  152         367  
626 51         191 my @names = grep { $seen{$_} } keys %$y;
  37         202  
627             }
628              
629             # Given the config passed to setup_exporter, which contains sugary opt list
630             # data, rewrite the opt lists into hashes, catch a few kinds of invalid
631             # configurations, and set up defaults. Since the config is a reference, it's
632             # rewritten in place.
633             my %valid_config_key;
634             BEGIN {
635             %valid_config_key =
636 16     16   115 map { $_ => 1 }
  144         32441  
637             qw(as collectors installer generator exports groups into into_level),
638             qw(exporter), # deprecated
639             }
640              
641             sub _assert_collector_names_ok {
642 51     51   115 my ($collectors) = @_;
643              
644 51         180 for my $reserved_name (grep { /\A[_A-Z]+\z/ } keys %$collectors) {
  37         201  
645 0 0       0 Carp::croak "unknown reserved collector name: $reserved_name"
646             if $reserved_name ne 'INIT';
647             }
648             }
649              
650             sub _rewrite_build_config {
651 53     53   105 my ($config) = @_;
652              
653 53 100       298 if (my @keys = grep { not exists $valid_config_key{$_} } keys %$config) {
  128         462  
654 1         187 Carp::croak "unknown options (@keys) passed to Sub::Exporter";
655             }
656              
657             Carp::croak q(into and into_level may not both be supplied to exporter)
658 52 100 100     325 if exists $config->{into} and exists $config->{into_level};
659              
660             # XXX: Remove after deprecation period.
661 51 50       147 if ($config->{exporter}) {
662 0         0 Carp::cluck "'exporter' argument to build_exporter is deprecated. Use 'installer' instead; the semantics are identical.";
663 0         0 $config->{installer} = delete $config->{exporter};
664             }
665              
666             Carp::croak q(into and into_level may not both be supplied to exporter)
667 51 50 66     141 if exists $config->{into} and exists $config->{into_level};
668              
669 51         119 for (qw(exports collectors)) {
670             $config->{$_} = Data::OptList::mkopt_hash(
671 102         7456 $config->{$_},
672             $_,
673             [ 'CODE', 'SCALAR' ],
674             );
675             }
676              
677 51         3061 _assert_collector_names_ok($config->{collectors});
678              
679 51 100       200 if (my @names = _key_intersection(@$config{qw(exports collectors)})) {
680 1         195 Carp::croak "names (@names) used in both collections and exports";
681             }
682              
683             $config->{groups} = Data::OptList::mkopt_hash(
684             $config->{groups},
685 50         237 'groups',
686             [
687             'HASH', # standard opt list
688             'ARRAY', # standard opt list
689             'CODE', # group generator
690             'SCALAR', # name of group generation method
691             ]
692             );
693              
694             # by default, export nothing
695 50   100     3784 $config->{groups}{default} ||= [];
696              
697             # by default, build an all-inclusive 'all' group
698 50   100     193 $config->{groups}{all} ||= [ keys %{ $config->{exports} } ];
  28         137  
699              
700 50   100     356 $config->{generator} ||= \&default_generator;
701 50   100     395 $config->{installer} ||= \&default_installer;
702             }
703              
704             sub build_exporter {
705 53     53 1 1398349 my ($config) = @_;
706              
707 53         169 _rewrite_build_config($config);
708              
709             my $import = sub {
710 105     105   1606352 my ($class) = shift;
711              
712             # XXX: clean this up -- rjbs, 2006-03-16
713 105 100       388 my $special = (ref $_[0]) ? shift(@_) : {};
714             Carp::croak q(into and into_level may not both be supplied to exporter)
715 105 100 100     524 if exists $special->{into} and exists $special->{into_level};
716              
717 104 50       346 if ($special->{exporter}) {
718 0         0 Carp::cluck "'exporter' special import argument is deprecated. Use 'installer' instead; the semantics are identical.";
719 0         0 $special->{installer} = delete $special->{exporter};
720             }
721              
722             my $into
723             = defined $special->{into} ? delete $special->{into}
724             : defined $special->{into_level} ? caller(delete $special->{into_level})
725             : defined $config->{into} ? $config->{into}
726             : defined $config->{into_level} ? caller($config->{into_level})
727 104 100       637 : caller(0);
    100          
    100          
    100          
728              
729 104   66     485 my $generator = delete $special->{generator} || $config->{generator};
730 104   66     366 my $installer = delete $special->{installer} || $config->{installer};
731              
732             # this builds a AOA, where the inner arrays are [ name => value_ref ]
733 104         442 my $import_args = Data::OptList::mkopt([ @_ ]);
734              
735             # is this right? defaults first or collectors first? -- rjbs, 2006-06-24
736 104 100       4432 $import_args = [ [ -default => undef ] ] unless @$import_args;
737              
738 104         313 my $collection = _collect_collections($config, $import_args, $class, $into);
739              
740 101         315 my $to_import = _expand_groups($class, $config, $import_args, $collection);
741              
742             # now, finally $import_arg is really the "to do" list
743 100         664 _do_import(
744             {
745             class => $class,
746             col => $collection,
747             config => $config,
748             into => $into,
749             generator => $generator,
750             installer => $installer,
751             },
752             $to_import,
753             );
754 50         343 };
755              
756 50         149 return $import;
757             }
758              
759             sub _do_import {
760 100     100   204 my ($arg, $to_import) = @_;
761              
762 100         215 my @todo;
763              
764 100         209 for my $pair (@$to_import) {
765 136         311 my ($name, $import_arg) = @$pair;
766              
767 136         243 my ($generator, $as);
768              
769 136 100 100     589 if ($import_arg and Params::Util::_CODELIKE($import_arg)) { ## no critic
770             # This is the case when a group generator has inserted name/code pairs.
771 10     10   16 $generator = sub { $import_arg };
  10         15  
772 10         12 $as = $name;
773             } else {
774 126 100       483 $import_arg = { $import_arg ? %$import_arg : () };
775              
776             Carp::croak qq("$name" is not exported by the $arg->{class} module)
777 126 100       701 unless exists $arg->{config}{exports}{$name};
778              
779 125         1217 $generator = $arg->{config}{exports}{$name};
780              
781 125 100       1016 $as = exists $import_arg->{-as} ? (delete $import_arg->{-as}) : $name;
782             }
783              
784             my $code = $arg->{generator}->(
785             {
786             class => $arg->{class},
787             name => $name,
788             arg => $import_arg,
789             col => $arg->{col},
790 135         656 generator => $generator,
791             }
792             );
793              
794 133         1103 push @todo, $as, $code;
795             }
796              
797             $arg->{installer}->(
798             {
799             class => $arg->{class},
800             into => $arg->{into},
801             col => $arg->{col},
802             },
803 97         491 \@todo,
804             );
805             }
806              
807             ## Cute idea, possibly for future use: also supply an "unimport" for:
808             ## no Module::Whatever qw(arg arg arg);
809             # sub _unexport {
810             # my (undef, undef, undef, undef, undef, $as, $into) = @_;
811             #
812             # if (ref $as eq 'SCALAR') {
813             # undef $$as;
814             # } elsif (ref $as) {
815             # Carp::croak "invalid reference type for $as: " . ref $as;
816             # } else {
817             # no strict 'refs';
818             # delete &{$into . '::' . $as};
819             # }
820             # }
821              
822             #pod =head2 default_generator
823             #pod
824             #pod This is Sub::Exporter's default generator. It takes bits of configuration that
825             #pod have been gathered during the import and turns them into a coderef that can be
826             #pod installed.
827             #pod
828             #pod my $code = default_generator(\%arg);
829             #pod
830             #pod Passed arguments are:
831             #pod
832             #pod class - the class on which the import method was called
833             #pod name - the name of the export being generated
834             #pod arg - the arguments to the generator
835             #pod col - the collections
836             #pod
837             #pod generator - the generator to be used to build the export (code or scalar ref)
838             #pod
839             #pod =cut
840              
841             sub default_generator {
842 107     107 1 212 my ($arg) = @_;
843 107         322 my ($class, $name, $generator) = @$arg{qw(class name generator)};
844              
845 107 100       242 if (not defined $generator) {
846 39 100       651 my $code = $class->can($name)
847             or Carp::croak "can't locate exported subroutine $name via $class";
848 37         111 return $code;
849             }
850              
851             # I considered making this "$class->$generator(" but it seems that
852             # overloading precedence would turn an overloaded-as-code generator object
853             # into a string before code. -- rjbs, 2006-06-11
854             return $generator->($class, $name, $arg->{arg}, $arg->{col})
855 68 100       320 if Params::Util::_CODELIKE($generator); ## no critic Private
856              
857             # This "must" be a scalar reference, to a generator method name.
858             # -- rjbs, 2006-12-05
859 2         38 return $class->$$generator($name, $arg->{arg}, $arg->{col});
860             }
861              
862             #pod =head2 default_installer
863             #pod
864             #pod This is Sub::Exporter's default installer. It does what Sub::Exporter
865             #pod promises: it installs code into the target package.
866             #pod
867             #pod default_installer(\%arg, \@to_export);
868             #pod
869             #pod Passed arguments are:
870             #pod
871             #pod into - the package into which exports should be delivered
872             #pod
873             #pod C<@to_export> is a list of name/value pairs. The default exporter assigns code
874             #pod (the values) to named slots (the names) in the given package. If the name is a
875             #pod scalar reference, the scalar reference is made to point to the code reference
876             #pod instead.
877             #pod
878             #pod =cut
879              
880             sub default_installer {
881 85     85 1 180 my ($arg, $to_export) = @_;
882              
883 85         1169 for (my $i = 0; $i < @$to_export; $i += 2) {
884 105         2552 my ($as, $code) = @$to_export[ $i, $i+1 ];
885              
886             # Allow as isa ARRAY to push onto an array?
887             # Allow into isa HASH to install name=>code into hash?
888              
889 105 100       917 if (ref $as eq 'SCALAR') {
    100          
890 2         61 $$as = $code;
891             } elsif (ref $as) {
892 2         492 Carp::croak "invalid reference type for $as: " . ref $as;
893             } else {
894             Sub::Install::reinstall_sub({
895             code => $code,
896             into => $arg->{into},
897 101         480 as => $as
898             });
899             }
900             }
901             }
902              
903             sub default_exporter {
904 0     0 0 0 Carp::cluck "default_exporter is deprecated; call default_installer instead; the semantics are identical";
905 0         0 goto &default_installer;
906             }
907              
908             #pod =head1 EXPORTS
909             #pod
910             #pod Sub::Exporter also offers its own exports: the C and
911             #pod C routines described above. It also provides a special "setup"
912             #pod collector, which will set up an exporter using the parameters passed to it.
913             #pod
914             #pod Note that the "setup" collector (seen in examples like the L above)
915             #pod uses C, not C. This means that the special
916             #pod arguments like "into" and "as" for C are not accepted here.
917             #pod Instead, you may write something like:
918             #pod
919             #pod use Sub::Exporter
920             #pod { into => 'Target::Package' },
921             #pod -setup => {
922             #pod -as => 'do_import',
923             #pod exports => [ ... ],
924             #pod }
925             #pod ;
926             #pod
927             #pod Finding a good reason for wanting to do this is left as an exercise for the
928             #pod reader.
929             #pod
930             #pod =cut
931              
932             setup_exporter({
933             exports => [
934             qw(setup_exporter build_exporter),
935             _import => sub { build_exporter($_[2]) },
936             ],
937             groups => {
938             all => [ qw(setup_exporter build_export) ],
939             },
940             collectors => { -setup => \&_setup },
941             });
942              
943             sub _setup {
944 18     18   42 my ($value, $arg) = @_;
945              
946 18 100       66 if (ref $value eq 'HASH') {
    100          
947 14         25 push @{ $arg->{import_args} }, [ _import => { -as => 'import', %$value } ];
  14         105  
948 14         84 return 1;
949             } elsif (ref $value eq 'ARRAY') {
950 2         3 push @{ $arg->{import_args} },
  2         10  
951             [ _import => { -as => 'import', exports => $value } ];
952 2         12 return 1;
953             }
954 2         353 return;
955             }
956              
957             #pod =head1 COMPARISONS
958             #pod
959             #pod There are a whole mess of exporters on the CPAN. The features included in
960             #pod Sub::Exporter set it apart from any existing Exporter. Here's a summary of
961             #pod some other exporters and how they compare.
962             #pod
963             #pod =over
964             #pod
965             #pod =item * L and co.
966             #pod
967             #pod This is the standard Perl exporter. Its interface is a little clunky, but it's
968             #pod fast and ubiquitous. It can do some things that Sub::Exporter can't: it can
969             #pod export things other than routines, it can import "everything in this group
970             #pod except this symbol," and some other more esoteric things. These features seem
971             #pod to go nearly entirely unused.
972             #pod
973             #pod It always exports things exactly as they appear in the exporting module; it
974             #pod can't rename or customize routines. Its groups ("tags") can't be nested.
975             #pod
976             #pod L is a whole lot like Exporter, but it does significantly less:
977             #pod it supports exporting symbols, but not groups, pattern matching, or negation.
978             #pod
979             #pod The fact that Sub::Exporter can't export symbols other than subroutines is
980             #pod a good idea, not a missing feature.
981             #pod
982             #pod For simple uses, setting up Sub::Exporter is about as easy as Exporter. For
983             #pod complex uses, Sub::Exporter makes hard things possible, which would not be
984             #pod possible with Exporter.
985             #pod
986             #pod When using a module that uses Sub::Exporter, users familiar with Exporter will
987             #pod probably see no difference in the basics. These two lines do about the same
988             #pod thing in whether the exporting module uses Exporter or Sub::Exporter.
989             #pod
990             #pod use Some::Module qw(foo bar baz);
991             #pod use Some::Module qw(foo :bar baz);
992             #pod
993             #pod The definition for exporting in Exporter.pm might look like this:
994             #pod
995             #pod package Some::Module;
996             #pod use base qw(Exporter);
997             #pod our @EXPORT_OK = qw(foo bar baz quux);
998             #pod our %EXPORT_TAGS = (bar => [ qw(bar baz) ]);
999             #pod
1000             #pod Using Sub::Exporter, it would look like this:
1001             #pod
1002             #pod package Some::Module;
1003             #pod use Sub::Exporter -setup => {
1004             #pod exports => [ qw(foo bar baz quux) ],
1005             #pod groups => { bar => [ qw(bar baz) ]}
1006             #pod };
1007             #pod
1008             #pod Sub::Exporter respects inheritance, so that a package may export inherited
1009             #pod routines, and will export the most inherited version. Exporting methods
1010             #pod without currying away the invocant is a bad idea, but Sub::Exporter allows you
1011             #pod to do just that -- and anyway, there are other uses for this feature, like
1012             #pod packages of exported subroutines which use inheritance specifically to allow
1013             #pod more specialized, but similar, packages.
1014             #pod
1015             #pod L provides a wrapper around the standard Exporter. It makes it
1016             #pod simpler to build groups, but doesn't provide any more functionality. Because
1017             #pod it is a front-end to Exporter, it will store your exporter's configuration in
1018             #pod global package variables.
1019             #pod
1020             #pod =item * Attribute-Based Exporters
1021             #pod
1022             #pod Some exporters use attributes to mark variables to export. L
1023             #pod supports exporting any kind of symbol, and supports groups. Using a module
1024             #pod like Exporter or Sub::Exporter, it's easy to look at one place and see what is
1025             #pod exported, but it's impossible to look at a variable definition and see whether
1026             #pod it is exported by that alone. Exporter::Simple makes this trade in reverse:
1027             #pod each variable's declaration includes its export definition, but there is no one
1028             #pod place to look to find a manifest of exports.
1029             #pod
1030             #pod More importantly, Exporter::Simple does not add any new features to those of
1031             #pod Exporter. In fact, like Exporter::Easy, it is just a front-end to Exporter, so
1032             #pod it ends up storing its configuration in global package variables. (This means
1033             #pod that there is one place to look for your exporter's manifest, actually. You
1034             #pod can inspect the C<@EXPORT> package variables, and other related package
1035             #pod variables, at runtime.)
1036             #pod
1037             #pod L isn't actually attribute based, but looks similar. Its syntax
1038             #pod is borrowed from Perl 6, and implemented by a source filter. It is a prototype
1039             #pod of an interface that is still being designed. It should probably be avoided
1040             #pod for production work. On the other hand, L implements
1041             #pod Perl 6-like exporting, but translates it into Perl 5 by providing attributes.
1042             #pod
1043             #pod =item * Other Exporters
1044             #pod
1045             #pod L wraps the standard Exporter to allow it to export symbols
1046             #pod with changed names.
1047             #pod
1048             #pod L performs a special kind of routine generation, giving each
1049             #pod importing package an instance of your class, and then exporting the instance's
1050             #pod methods as normal routines. (Sub::Exporter, of course, can easily emulate this
1051             #pod behavior, as shown above.)
1052             #pod
1053             #pod L implements a form of renaming (using its C<_map> argument)
1054             #pod and of prefixing, and implements groups. It also avoids using package
1055             #pod variables for its configuration.
1056             #pod
1057             #pod =back
1058             #pod
1059             #pod =head1 TODO
1060             #pod
1061             #pod =cut
1062              
1063             #pod =over
1064             #pod
1065             #pod =item * write a set of longer, more demonstrative examples
1066             #pod
1067             #pod =item * solidify the "custom exporter" interface (see C<&default_exporter>)
1068             #pod
1069             #pod =item * add an "always" group
1070             #pod
1071             #pod =back
1072             #pod
1073             #pod =head1 THANKS
1074             #pod
1075             #pod Hans Dieter Pearcey provided helpful advice while I was writing Sub::Exporter.
1076             #pod Ian Langworth and Shawn Sorichetti asked some good questions and helped me
1077             #pod improve my documentation quite a bit. Yuval Kogman helped me find a bunch of
1078             #pod little problems.
1079             #pod
1080             #pod Thanks, friends!
1081             #pod
1082             #pod =head1 BUGS
1083             #pod
1084             #pod Please report any bugs or feature requests through the web interface at
1085             #pod L. I will be notified, and then you'll automatically be
1086             #pod notified of progress on your bug as I make changes.
1087             #pod
1088             #pod =cut
1089              
1090             "jn8:32"; # <-- magic true value
1091              
1092             __END__