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.
7 package BASIS::Sub::Exporter;
9 $BASIS::Sub::Exporter::VERSION = '0.984';
11 # ABSTRACT: a sophisticated exporter for custom-built routines
14 use BASIS::Data::OptList 0.100 ();
15 use BASIS::Params::Util 0.14 (); # _CODELIKE
16 use BASIS::Sub::Install 0.92 ();
19 # Given a potential import name, this returns the group name -- if it's got a
24 return if (index q{-:}, (substr $name, 0, 1)) == -1;
25 return substr $name, 1;
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.
33 my ($class, $config, $groups, $collection, $seen, $merge) = @_;
36 my @groups = @$groups;
38 for my $i (reverse 0 .. $#groups) {
39 if (my $group_name = _group_name($groups[$i][0])) {
40 my $seen = { %$seen }; # faux-dynamic scoping
42 splice @groups, $i, 1,
43 _expand_group($class, $config, $groups[$i], $collection, $seen, $merge);
45 # there's nothing to munge in this export's args
46 next unless my %merge = %$merge;
48 # we have things to merge in; do so
49 my $prefix = (delete $merge{-prefix}) || '';
50 my $suffix = (delete $merge{-suffix}) || '';
53 BASIS::Params::Util::_CODELIKE($groups[$i][1]) ## no critic Private
55 BASIS::Params::Util::_SCALAR0($groups[$i][1]) ## no critic Private
57 # this entry was build by a group generator
58 $groups[$i][0] = $prefix . $groups[$i][0] . $suffix;
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;
65 $groups[$i][1] = { %{ $groups[$i][1] }, %merge, -as => $as };
73 # \@group is a name/value pair from an opt list.
75 my ($class, $config, $group, $collection, $seen, $merge) = @_;
78 my ($group_name, $group_arg) = @$group;
79 $group_name = _group_name($group_name);
81 Carp::croak qq(group "$group_name" is not exported by the $class module)
82 unless exists $config->{groups}{$group_name};
84 return if $seen->{$group_name}++;
87 my $prefix = (delete $merge->{-prefix}||'') . ($group_arg->{-prefix}||'');
88 my $suffix = ($group_arg->{-suffix}||'') . (delete $merge->{-suffix}||'');
92 ($prefix ? (-prefix => $prefix) : ()),
93 ($suffix ? (-suffix => $suffix) : ()),
97 my $exports = $config->{groups}{$group_name};
100 BASIS::Params::Util::_CODELIKE($exports) ## no critic Private
102 BASIS::Params::Util::_SCALAR0($exports) ## no critic Private
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};
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);
115 Carp::croak qq(group generator "$group_name" did not return a hashref)
116 if ref $group ne 'HASH';
118 my $stuff = [ map { [ $_ => $group->{$_} ] } keys %$group ];
120 _expand_groups($class, $config, $stuff, $collection, $seen, $merge)
124 = BASIS::Data::OptList::mkopt($exports, "$group_name exports");
127 _expand_groups($class, $config, $exports, $collection, $seen, $merge)
132 sub _mk_collection_builder {
133 my ($col, $etc) = @_;
134 my ($config, $import_args, $class, $into) = @$etc;
138 my ($collection) = @_;
139 my ($name, $value) = @$collection;
141 Carp::croak "collection $name provided multiple times in import"
144 if (ref(my $hook = $config->{collectors}{$name})) {
148 import_args => $import_args,
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);
157 Carp::croak $error_msg unless $hook->($value, $arg);
161 $col->{ $name } = $value;
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) = @_;
171 = map { splice @$import_args, $_, 1 }
172 grep { exists $config->{collectors}{ $import_args->[$_][0] } }
173 reverse 0 .. $#$import_args;
175 unshift @collections, [ INIT => {} ] if $config->{collectors}{INIT};
178 my $builder = _mk_collection_builder($col, \@_);
179 for my $collection (@collections) {
180 $builder->($collection)
190 Carp::croak 'into and into_level may not both be supplied to exporter'
191 if exists $config->{into} and exists $config->{into_level};
193 my $as = delete $config->{as} || 'import';
195 = exists $config->{into} ? delete $config->{into}
196 : exists $config->{into_level} ? caller(delete $config->{into_level})
199 my $import = build_exporter($config);
201 BASIS::Sub::Install::reinstall_sub({
209 sub _key_intersection {
211 my %seen = map { $_ => 1 } keys %$x;
212 my @names = grep { $seen{$_} } keys %$y;
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;
223 qw(as collectors installer generator exports groups into into_level),
224 qw(exporter), # deprecated
227 sub _assert_collector_names_ok {
228 my ($collectors) = @_;
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';
236 sub _rewrite_build_config {
239 if (my @keys = grep { not exists $valid_config_key{$_} } keys %$config) {
240 Carp::croak "unknown options (@keys) passed to BASIS::Sub::Exporter";
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};
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};
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};
255 for (qw(exports collectors)) {
256 $config->{$_} = BASIS::Data::OptList::mkopt_hash(
259 [ 'CODE', 'SCALAR' ],
263 _assert_collector_names_ok($config->{collectors});
265 if (my @names = _key_intersection(@$config{qw(exports collectors)})) {
266 Carp::croak "names (@names) used in both collections and exports";
269 $config->{groups} = BASIS::Data::OptList::mkopt_hash(
273 'HASH', # standard opt list
274 'ARRAY', # standard opt list
275 'CODE', # group generator
276 'SCALAR', # name of group generation method
280 # by default, export nothing
281 $config->{groups}{default} ||= [];
283 # by default, build an all-inclusive 'all' group
284 $config->{groups}{all} ||= [ keys %{ $config->{exports} } ];
286 $config->{generator} ||= \&default_generator;
287 $config->{installer} ||= \&default_installer;
293 _rewrite_build_config($config);
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};
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};
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})
315 my $generator = delete $special->{generator} || $config->{generator};
316 my $installer = delete $special->{installer} || $config->{installer};
318 # this builds a AOA, where the inner arrays are [ name => value_ref ]
319 my $import_args = BASIS::Data::OptList::mkopt([ @_ ]);
321 # is this right? defaults first or collectors first? -- rjbs, 2006-06-24
322 $import_args = [ [ -default => undef ] ] unless @$import_args;
324 my $collection = _collect_collections($config, $import_args, $class, $into);
326 my $to_import = _expand_groups($class, $config, $import_args, $collection);
328 # now, finally $import_arg is really the "to do" list
335 generator => $generator,
336 installer => $installer,
346 my ($arg, $to_import) = @_;
350 for my $pair (@$to_import) {
351 my ($name, $import_arg) = @$pair;
353 my ($generator, $as);
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 };
360 $import_arg = { $import_arg ? %$import_arg : () };
362 Carp::croak qq("$name" is not exported by the $arg->{class} module)
363 unless exists $arg->{config}{exports}{$name};
365 $generator = $arg->{config}{exports}{$name};
367 $as = exists $import_arg->{-as} ? (delete $import_arg->{-as}) : $name;
370 my $code = $arg->{generator}->(
372 class => $arg->{class},
376 generator => $generator,
380 push @todo, $as, $code;
385 class => $arg->{class},
386 into => $arg->{into},
393 # Cute idea, possibly for future use: also supply an "unimport" for:
394 # no Module::Whatever qw(arg arg arg);
396 # my (undef, undef, undef, undef, undef, $as, $into) = @_;
398 # if (ref $as eq 'SCALAR') {
400 # } elsif (ref $as) {
401 # Carp::croak "invalid reference type for $as: " . ref $as;
404 # delete &{$into . '::' . $as};
409 sub default_generator {
411 my ($class, $name, $generator) = @$arg{qw(class name generator)};
413 if (not defined $generator) {
414 my $code = $class->can($name)
415 or Carp::croak "can't locate exported subroutine $name via $class";
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
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});
431 sub default_installer {
432 my ($arg, $to_export) = @_;
434 for (my $i = 0; $i < @$to_export; $i += 2) {
435 my ($as, $code) = @$to_export[ $i, $i+1 ];
437 # Allow as isa ARRAY to push onto an array?
438 # Allow into isa HASH to install name=>code into hash?
440 if (ref $as eq 'SCALAR') {
443 Carp::croak "invalid reference type for $as: " . ref $as;
445 BASIS::Sub::Install::reinstall_sub({
447 into => $arg->{into},
454 sub default_exporter {
455 Carp::cluck "default_exporter is deprecated; call default_installer instead; the semantics are identical";
456 goto &default_installer;
462 qw(setup_exporter build_exporter),
463 _import => sub { build_exporter($_[2]) },
466 all => [ qw(setup_exporter build_export) ],
468 collectors => { -setup => \&_setup },
472 my ($value, $arg) = @_;
474 if (ref $value eq 'HASH') {
475 push @{ $arg->{import_args} }, [ _import => { -as => 'import', %$value } ];
477 } elsif (ref $value eq 'ARRAY') {
478 push @{ $arg->{import_args} },
479 [ _import => { -as => 'import', exports => $value } ];
487 "jn8:32"; # <-- magic true value
494 BASIS::Sub::Exporter - a sophisticated exporter for custom-built routines
502 BASIS::Sub::Exporter must be used in two places. First, in an exporting module:
504 # in the exporting module:
505 package Text::Tweaker;
506 use BASIS::Sub::Exporter -setup => {
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,
513 collectors => [ 'defaults' ],
516 Then, in an importing module:
518 # in the importing module:
521 indent => { margin => 5 },
522 reformat => { width => 79, justify => 'full', -as => 'prettify_text' },
523 defaults => { eol => 'CRLF' };
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
532 B<ACHTUNG!> If you're not familiar with Exporter or exporting, read
533 L<BASIS::Sub::Exporter::Tutorial> first!
535 =head2 Why Generators?
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.
541 If your module's consumers get a routine that works like this:
543 use Data::Analyze qw(analyze);
544 my $value = analyze($data, $tolerance, $passes);
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:
551 analyze => { tolerance => 0.10, passes => 10, -as => analyze10 },
552 analyze => { tolerance => 0.15, passes => 50, -as => analyze50 };
554 my $value = analyze10($data);
556 The generator for that would look something like this:
559 my ($class, $name, $arg) = @_;
563 my $tolerance = shift || $arg->{tolerance};
564 my $passes = shift || $arg->{passes};
566 analyze($data, $tolerance, $passes);
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.
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
578 use Data::Analyze qw(analyze);
579 $Data::Analyze::default_tolerance = 0.10;
580 $Data::Analyze::default_passes = 10;
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.
586 Generators can also allow you to export class methods to be called as
589 package Data::Methodical;
590 use BASIS::Sub::Exporter -setup => { exports => { some_method => \&_curry_class } };
593 my ($class, $name) = @_;
594 sub { $class->$name(@_); };
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.
603 =head2 Other Customizations
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.
609 Consider the following code:
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
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.
620 How much easier to write:
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_' };
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>.
629 =head1 EXPORTER CONFIGURATION
631 You can configure an exporter for your package by using BASIS::Sub::Exporter like so:
634 use BASIS::Sub::Exporter
635 -setup => { exports => [ qw(function1 function2 function3) ] };
637 This is the simplest way to use the exporter, and is basically equivalent to
641 use base qw(Exporter);
642 our @EXPORT_OK = qw(function1 function2 function2);
644 Any basic use of BASIS::Sub::Exporter will look like this:
647 use BASIS::Sub::Exporter -setup => \%config;
649 The following keys are valid in C<%config>:
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
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
660 In addition to the basic options above, a few more advanced options may be
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
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.
670 generator - a callback used to produce the code that will be installed
671 default: BASIS::Sub::Exporter::default_generator
673 installer - a callback used to install the code produced by the generator
674 default: BASIS::Sub::Exporter::default_installer
676 For information on how these callbacks are used, see the documentation for
677 C<L</default_generator>> and C<L</default_installer>>.
679 =head2 Export Configuration
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:
684 { exports => [ qw(foo bar baz), quux => \&quux_generator ] }
687 { foo => undef, bar => undef, baz => undef, quux => \&quux_generator } }
689 Generators are code that return coderefs. They are called with four
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
697 Given the configuration in the L</SYNOPSIS>, the following C<use> statement:
700 reformat => { -as => 'make_narrow', width => 33 },
701 defaults => { eol => 'CR' };
703 would result in the following call to C<&build_reformatter>:
705 my $code = build_reformatter(
708 { width => 33 }, # note that -as is not passed in
709 { defaults => { eol => 'CR' } },
712 The returned coderef (C<$code>) would then be installed as C<make_narrow> in the
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
720 =head2 Group Configuration
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.
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>.
730 default => [ qw(reformat) ],
731 shorteners => [ qw(squish trim) ],
734 reformat => { -as => 'email_format', width => 72 }
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:
741 use Text::Tweaker qw(-shorteners);
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.
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.
753 This example shows a simple use of the group generator.
755 package Data::Crypto;
756 use BASIS::Sub::Exporter -setup => { groups => { cipher => \&build_cipher_group } };
758 sub build_cipher_group {
759 my ($class, $group, $arg) = @_;
760 my ($encode, $decode) = build_codec($arg->{secret});
761 return { cipher => $encode, decipher => $decode };
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.
767 =head3 Default Groups
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.
773 Another group is also created if not defined: C<all>. The C<all> group
774 contains all the exports from the exports list.
776 =head2 Collector Configuration
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
782 For example, the C<build_analyzer> generator that we saw above could be
786 my ($class, $name, $arg, $col) = @_;
790 my $tolerance = shift || $arg->{tolerance} || $col->{defaults}{tolerance};
791 my $passes = shift || $arg->{passes} || $col->{defaults}{passes};
793 analyze($data, $tolerance, $passes);
797 That would allow the import to specify global defaults for his imports:
801 analyze => { tolerance => 0.10, -as => analyze10 },
802 analyze => { tolerance => 0.15, passes => 50, -as => analyze50 },
803 defaults => { passes => 10 };
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);
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
815 collectors => { defaults => sub { return (exists $_[0]->{data}) ? 0 : 1 } }
817 Collector coderefs can also be used as hooks to perform arbitrary actions
818 before anything is exported.
820 When the coderef is called, it is passed the value of the collection and a
821 hashref containing the following entries:
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
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.
834 =head1 CALLING THE EXPORTER
836 Arguments to the exporter (that is, the arguments after the module name in a
837 C<use> statement) are parsed as follows:
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.
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:
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
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:
854 -as - where to install the exported sub
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.
861 =head2 Special Exporter Arguments
863 The generated exporter accept some special options, which may be passed as the
864 first argument, in a hashref.
873 These override the same-named configuration options described in L</EXPORTER
878 =head2 setup_exporter
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:
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
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.
895 Providing both C<into> and C<into_level> will cause an exception to be thrown.
897 The exporter is built by C<L</build_exporter>>.
899 =head2 build_exporter
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.
905 Usually, this method is called by C<L</setup_exporter>>, which then installs
906 the exporter as a package's import routine.
908 =head2 default_generator
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
914 my $code = default_generator(\%arg);
916 Passed arguments are:
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
923 generator - the generator to be used to build the export (code or scalar ref)
925 =head2 default_installer
927 This is BASIS::Sub::Exporter's default installer. It does what BASIS::Sub::Exporter
928 promises: it installs code into the target package.
930 default_installer(\%arg, \@to_export);
932 Passed arguments are:
934 into - the package into which exports should be delivered
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
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.
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:
952 use BASIS::Sub::Exporter
953 { into => 'Target::Package' },
960 Finding a good reason for wanting to do this is left as as exercise for the
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.
971 =item * L<Exporter> and co.
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.
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.
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.
985 The fact that BASIS::Sub::Exporter can't export symbols other than subroutines is
986 a good idea, not a missing feature.
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.
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.
996 use Some::Module qw(foo bar baz);
997 use Some::Module qw(foo :bar baz);
999 The definition for exporting in Exporter.pm might look like this:
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) ]);
1006 Using BASIS::Sub::Exporter, it would look like this:
1008 package Some::Module;
1009 use BASIS::Sub::Exporter -setup => {
1010 exports => [ qw(foo bar baz quux) ],
1011 groups => { bar => [ qw(bar baz) ]}
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.
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.
1026 =item * Attribute-Based Exporters
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.
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.)
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.
1049 =item * Other Exporters
1051 L<Exporter::Renaming> wraps the standard Exporter to allow it to export symbols
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.)
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.
1069 =item * write a set of longer, more demonstrative examples
1071 =item * solidify the "custom exporter" interface (see C<&default_exporter>)
1073 =item * add an "always" group
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
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.
1094 Ricardo Signes <rjbs@cpan.org>
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.
1099 =head1 COPYRIGHT AND LICENSE
1101 This software is copyright (c) 2007 by Ricardo Signes.
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.