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