D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
home
/
vblioqus
/
karachi777.vip
/
in
/
106014
/
900508
/
Filename :
Sub.tar
back
Copy
Install.pm 0000644 00000030357 15154224273 0006525 0 ustar 00 use strict; use warnings; package Sub::Install; # ABSTRACT: install subroutines into packages easily $Sub::Install::VERSION = '0.928'; use Carp; use Scalar::Util (); #pod =head1 SYNOPSIS #pod #pod use Sub::Install; #pod #pod Sub::Install::install_sub({ #pod code => sub { ... }, #pod into => $package, #pod as => $subname #pod }); #pod #pod =head1 DESCRIPTION #pod #pod This module makes it easy to install subroutines into packages without the #pod unsightly mess of C<no strict> or typeglobs lying about where just anyone can #pod see them. #pod #pod =func install_sub #pod #pod Sub::Install::install_sub({ #pod code => \&subroutine, #pod into => "Finance::Shady", #pod as => 'launder', #pod }); #pod #pod This routine installs a given code reference into a package as a normal #pod subroutine. The above is equivalent to: #pod #pod no strict 'refs'; #pod *{"Finance::Shady" . '::' . "launder"} = \&subroutine; #pod #pod If C<into> is not given, the sub is installed into the calling package. #pod #pod If C<code> is not a code reference, it is looked for as an existing sub in the #pod package named in the C<from> parameter. If C<from> is not given, it will look #pod in the calling package. #pod #pod If C<as> is not given, and if C<code> is a name, C<as> will default to C<code>. #pod If C<as> is not given, but if C<code> is a code ref, Sub::Install will try to #pod find the name of the given code ref and use that as C<as>. #pod #pod That means that this code: #pod #pod Sub::Install::install_sub({ #pod code => 'twitch', #pod from => 'Person::InPain', #pod into => 'Person::Teenager', #pod as => 'dance', #pod }); #pod #pod is the same as: #pod #pod package Person::Teenager; #pod #pod Sub::Install::install_sub({ #pod code => Person::InPain->can('twitch'), #pod as => 'dance', #pod }); #pod #pod =func reinstall_sub #pod #pod This routine behaves exactly like C<L</install_sub>>, but does not emit a #pod warning if warnings are on and the destination is already defined. #pod #pod =cut sub _name_of_code { my ($code) = @_; require B; my $name = B::svref_2object($code)->GV->NAME; return $name unless $name =~ /\A__ANON__/; return; } # See also Params::Util, to which this code was donated. sub _CODELIKE { (Scalar::Util::reftype($_[0])||'') eq 'CODE' || Scalar::Util::blessed($_[0]) && (overload::Method($_[0],'&{}') ? $_[0] : undef); } # do the heavy lifting sub _build_public_installer { my ($installer) = @_; sub { my ($arg) = @_; my ($calling_pkg) = caller(0); # I'd rather use ||= but I'm whoring for Devel::Cover. for (qw(into from)) { $arg->{$_} = $calling_pkg unless $arg->{$_} } # This is the only absolutely required argument, in many cases. Carp::croak "named argument 'code' is not optional" unless $arg->{code}; if (_CODELIKE($arg->{code})) { $arg->{as} ||= _name_of_code($arg->{code}); } else { Carp::croak "couldn't find subroutine named $arg->{code} in package $arg->{from}" unless my $code = $arg->{from}->can($arg->{code}); $arg->{as} = $arg->{code} unless $arg->{as}; $arg->{code} = $code; } Carp::croak "couldn't determine name under which to install subroutine" unless $arg->{as}; $installer->(@$arg{qw(into as code) }); } } # do the ugly work my $_misc_warn_re; my $_redef_warn_re; BEGIN { $_misc_warn_re = qr/ Prototype\ mismatch:\ sub\ .+? | Constant subroutine .+? redefined /x; $_redef_warn_re = qr/Subroutine\ .+?\ redefined/x; } my $eow_re; BEGIN { $eow_re = qr/ at .+? line \d+\.\Z/ }; sub _do_with_warn { my ($arg) = @_; my $code = delete $arg->{code}; my $wants_code = sub { my $code = shift; sub { my $warn = $SIG{__WARN__} ? $SIG{__WARN__} : sub { warn @_ }; ## no critic local $SIG{__WARN__} = sub { my ($error) = @_; for (@{ $arg->{suppress} }) { return if $error =~ $_; } for (@{ $arg->{croak} }) { if (my ($base_error) = $error =~ /\A($_) $eow_re/x) { Carp::croak $base_error; } } for (@{ $arg->{carp} }) { if (my ($base_error) = $error =~ /\A($_) $eow_re/x) { return $warn->(Carp::shortmess $base_error); } } ($arg->{default} || $warn)->($error); }; $code->(@_); }; }; return $wants_code->($code) if $code; return $wants_code; } sub _installer { sub { my ($pkg, $name, $code) = @_; no strict 'refs'; ## no critic ProhibitNoStrict *{"$pkg\::$name"} = $code; return $code; } } BEGIN { *_ignore_warnings = _do_with_warn({ carp => [ $_misc_warn_re, $_redef_warn_re ] }); *install_sub = _build_public_installer(_ignore_warnings(_installer)); *_carp_warnings = _do_with_warn({ carp => [ $_misc_warn_re ], suppress => [ $_redef_warn_re ], }); *reinstall_sub = _build_public_installer(_carp_warnings(_installer)); *_install_fatal = _do_with_warn({ code => _installer, croak => [ $_redef_warn_re ], }); } #pod =func install_installers #pod #pod This routine is provided to allow Sub::Install compatibility with #pod Sub::Installer. It installs C<install_sub> and C<reinstall_sub> methods into #pod the package named by its argument. #pod #pod Sub::Install::install_installers('Code::Builder'); # just for us, please #pod Code::Builder->install_sub({ name => $code_ref }); #pod #pod Sub::Install::install_installers('UNIVERSAL'); # feeling lucky, punk? #pod Anything::At::All->install_sub({ name => $code_ref }); #pod #pod The installed installers are similar, but not identical, to those provided by #pod Sub::Installer. They accept a single hash as an argument. The key/value pairs #pod are used as the C<as> and C<code> parameters to the C<install_sub> routine #pod detailed above. The package name on which the method is called is used as the #pod C<into> parameter. #pod #pod Unlike Sub::Installer's C<install_sub> will not eval strings into code, but #pod will look for named code in the calling package. #pod #pod =cut sub install_installers { my ($into) = @_; for my $method (qw(install_sub reinstall_sub)) { my $code = sub { my ($package, $subs) = @_; my ($caller) = caller(0); my $return; for (my ($name, $sub) = %$subs) { $return = Sub::Install->can($method)->({ code => $sub, from => $caller, into => $package, as => $name }); } return $return; }; install_sub({ code => $code, into => $into, as => $method }); } } #pod =head1 EXPORTS #pod #pod Sub::Install exports C<install_sub> and C<reinstall_sub> only if they are #pod requested. #pod #pod =head2 exporter #pod #pod Sub::Install has a never-exported subroutine called C<exporter>, which is used #pod to implement its C<import> routine. It takes a hashref of named arguments, #pod only one of which is currently recognize: C<exports>. This must be an arrayref #pod of subroutines to offer for export. #pod #pod This routine is mainly for Sub::Install's own consumption. Instead, consider #pod L<Sub::Exporter>. #pod #pod =cut sub exporter { my ($arg) = @_; my %is_exported = map { $_ => undef } @{ $arg->{exports} }; sub { my $class = shift; my $target = caller; for (@_) { Carp::croak "'$_' is not exported by $class" if !exists $is_exported{$_}; install_sub({ code => $_, from => $class, into => $target }); } } } BEGIN { *import = exporter({ exports => [ qw(install_sub reinstall_sub) ] }); } #pod =head1 SEE ALSO #pod #pod =over #pod #pod =item L<Sub::Installer> #pod #pod This module is (obviously) a reaction to Damian Conway's Sub::Installer, which #pod does the same thing, but does it by getting its greasy fingers all over #pod UNIVERSAL. I was really happy about the idea of making the installation of #pod coderefs less ugly, but I couldn't bring myself to replace the ugliness of #pod typeglobs and loosened strictures with the ugliness of UNIVERSAL methods. #pod #pod =item L<Sub::Exporter> #pod #pod This is a complete Exporter.pm replacement, built atop Sub::Install. #pod #pod =back #pod #pod =head1 EXTRA CREDITS #pod #pod Several of the tests are adapted from tests that shipped with Damian Conway's #pod Sub-Installer distribution. #pod #pod =cut 1; __END__ =pod =encoding UTF-8 =head1 NAME Sub::Install - install subroutines into packages easily =head1 VERSION version 0.928 =head1 SYNOPSIS use Sub::Install; Sub::Install::install_sub({ code => sub { ... }, into => $package, as => $subname }); =head1 DESCRIPTION This module makes it easy to install subroutines into packages without the unsightly mess of C<no strict> or typeglobs lying about where just anyone can see them. =head1 FUNCTIONS =head2 install_sub Sub::Install::install_sub({ code => \&subroutine, into => "Finance::Shady", as => 'launder', }); This routine installs a given code reference into a package as a normal subroutine. The above is equivalent to: no strict 'refs'; *{"Finance::Shady" . '::' . "launder"} = \&subroutine; If C<into> is not given, the sub is installed into the calling package. If C<code> is not a code reference, it is looked for as an existing sub in the package named in the C<from> parameter. If C<from> is not given, it will look in the calling package. If C<as> is not given, and if C<code> is a name, C<as> will default to C<code>. If C<as> is not given, but if C<code> is a code ref, Sub::Install will try to find the name of the given code ref and use that as C<as>. That means that this code: Sub::Install::install_sub({ code => 'twitch', from => 'Person::InPain', into => 'Person::Teenager', as => 'dance', }); is the same as: package Person::Teenager; Sub::Install::install_sub({ code => Person::InPain->can('twitch'), as => 'dance', }); =head2 reinstall_sub This routine behaves exactly like C<L</install_sub>>, but does not emit a warning if warnings are on and the destination is already defined. =head2 install_installers This routine is provided to allow Sub::Install compatibility with Sub::Installer. It installs C<install_sub> and C<reinstall_sub> methods into the package named by its argument. Sub::Install::install_installers('Code::Builder'); # just for us, please Code::Builder->install_sub({ name => $code_ref }); Sub::Install::install_installers('UNIVERSAL'); # feeling lucky, punk? Anything::At::All->install_sub({ name => $code_ref }); The installed installers are similar, but not identical, to those provided by Sub::Installer. They accept a single hash as an argument. The key/value pairs are used as the C<as> and C<code> parameters to the C<install_sub> routine detailed above. The package name on which the method is called is used as the C<into> parameter. Unlike Sub::Installer's C<install_sub> will not eval strings into code, but will look for named code in the calling package. =head1 EXPORTS Sub::Install exports C<install_sub> and C<reinstall_sub> only if they are requested. =head2 exporter Sub::Install has a never-exported subroutine called C<exporter>, which is used to implement its C<import> routine. It takes a hashref of named arguments, only one of which is currently recognize: C<exports>. This must be an arrayref of subroutines to offer for export. This routine is mainly for Sub::Install's own consumption. Instead, consider L<Sub::Exporter>. =head1 SEE ALSO =over =item L<Sub::Installer> This module is (obviously) a reaction to Damian Conway's Sub::Installer, which does the same thing, but does it by getting its greasy fingers all over UNIVERSAL. I was really happy about the idea of making the installation of coderefs less ugly, but I couldn't bring myself to replace the ugliness of typeglobs and loosened strictures with the ugliness of UNIVERSAL methods. =item L<Sub::Exporter> This is a complete Exporter.pm replacement, built atop Sub::Install. =back =head1 EXTRA CREDITS Several of the tests are adapted from tests that shipped with Damian Conway's Sub-Installer distribution. =head1 AUTHOR Ricardo SIGNES <rjbs@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2005 by Ricardo SIGNES. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Exporter/Util.pm 0000644 00000021345 15154224274 0007642 0 ustar 00 use strict; use warnings; package Sub::Exporter::Util; { $Sub::Exporter::Util::VERSION = '0.987'; } # ABSTRACT: utilities to make Sub::Exporter easier use Data::OptList (); use Params::Util (); sub curry_method { my $override_name = shift; sub { my ($class, $name) = @_; $name = $override_name if defined $override_name; sub { $class->$name(@_); }; } } BEGIN { *curry_class = \&curry_method; } sub curry_chain { # In the future, we can make \%arg an optional prepend, like the "special" # args to the default Sub::Exporter-generated import routine. my (@opt_list) = @_; my $pairs = Data::OptList::mkopt(\@opt_list, 'args', 'ARRAY'); sub { my ($class) = @_; sub { my $next = $class; for my $i (0 .. $#$pairs) { my $pair = $pairs->[ $i ]; unless (Params::Util::_INVOCANT($next)) { ## no critic Private my $str = defined $next ? "'$next'" : 'undef'; Carp::croak("can't call $pair->[0] on non-invocant $str") } my ($method, $args) = @$pair; if ($i == $#$pairs) { return $next->$method($args ? @$args : ()); } else { $next = $next->$method($args ? @$args : ()); } } }; } } # =head2 name_map # # This utility returns an list to be used in specify export generators. For # example, the following: # # exports => { # name_map( # '_?_gen' => [ qw(fee fie) ], # '_make_?' => [ qw(foo bar) ], # ), # } # # is equivalent to: # # exports => { # name_map( # fee => \'_fee_gen', # fie => \'_fie_gen', # foo => \'_make_foo', # bar => \'_make_bar', # ), # } # # This can save a lot of typing, when providing many exports with similarly-named # generators. # # =cut # # sub name_map { # my (%groups) = @_; # # my %map; # # while (my ($template, $names) = each %groups) { # for my $name (@$names) { # (my $export = $template) =~ s/\?/$name/ # or Carp::croak 'no ? found in name_map template'; # # $map{ $name } = \$export; # } # } # # return %map; # } sub merge_col { my (%groups) = @_; my %merged; while (my ($default_name, $group) = each %groups) { while (my ($export_name, $gen) = each %$group) { $merged{$export_name} = sub { my ($class, $name, $arg, $col) = @_; my $merged_arg = exists $col->{$default_name} ? { %{ $col->{$default_name} }, %$arg } : $arg; if (Params::Util::_CODELIKE($gen)) { ## no critic Private $gen->($class, $name, $merged_arg, $col); } else { $class->$$gen($name, $merged_arg, $col); } } } } return %merged; } sub __mixin_class_for { my ($class, $mix_into) = @_; require Package::Generator; my $mixin_class = Package::Generator->new_package({ base => "$class\:\:__mixin__", }); ## no critic (ProhibitNoStrict) no strict 'refs'; if (ref $mix_into) { unshift @{"$mixin_class" . "::ISA"}, ref $mix_into; } else { unshift @{"$mix_into" . "::ISA"}, $mixin_class; } return $mixin_class; } sub mixin_installer { sub { my ($arg, $to_export) = @_; my $mixin_class = __mixin_class_for($arg->{class}, $arg->{into}); bless $arg->{into} => $mixin_class if ref $arg->{into}; Sub::Exporter::default_installer( { %$arg, into => $mixin_class }, $to_export, ); }; } sub mixin_exporter { Carp::cluck "mixin_exporter is deprecated; use mixin_installer instead; it behaves identically"; return mixin_installer; } sub like { sub { my ($value, $arg) = @_; Carp::croak "no regex supplied to regex group generator" unless $value; # Oh, qr//, how you bother me! See the p5p thread from around now about # fixing this problem... too bad it won't help me. -- rjbs, 2006-04-25 my @values = eval { $value->isa('Regexp') } ? ($value, undef) : @$value; while (my ($re, $opt) = splice @values, 0, 2) { Carp::croak "given pattern for regex group generater is not a Regexp" unless eval { $re->isa('Regexp') }; my @exports = keys %{ $arg->{config}->{exports} }; my @matching = grep { $_ =~ $re } @exports; my %merge = $opt ? %$opt : (); my $prefix = (delete $merge{-prefix}) || ''; my $suffix = (delete $merge{-suffix}) || ''; for my $name (@matching) { my $as = $prefix . $name . $suffix; push @{ $arg->{import_args} }, [ $name => { %merge, -as => $as } ]; } } 1; } } use Sub::Exporter -setup => { exports => [ qw( like name_map merge_col curry_method curry_class curry_chain mixin_installer mixin_exporter ) ] }; 1; __END__ =pod =head1 NAME Sub::Exporter::Util - utilities to make Sub::Exporter easier =head1 VERSION version 0.987 =head1 DESCRIPTION This module provides a number of utility functions for performing common or useful operations when setting up a Sub::Exporter configuration. All of the utilities may be exported, but none are by default. =head1 THE UTILITIES =head2 curry_method exports => { some_method => curry_method, } This utility returns a generator which will produce an invocant-curried version of a method. In other words, it will export a method call with the exporting class built in as the invocant. A module importing the code some the above example might do this: use Some::Module qw(some_method); my $x = some_method; This would be equivalent to: use Some::Module; my $x = Some::Module->some_method; If Some::Module is subclassed and the subclass's import method is called to import C<some_method>, the subclass will be curried in as the invocant. If an argument is provided for C<curry_method> it is used as the name of the curried method to export. This means you could export a Widget constructor like this: exports => { widget => curry_method('new') } This utility may also be called as C<curry_class>, for backwards compatibility. =head2 curry_chain C<curry_chain> behaves like C<L</curry_method>>, but is meant for generating exports that will call several methods in succession. exports => { reticulate => curry_chain( new => gather_data => analyze => [ detail => 100 ] => 'results' ), } If imported from Spliner, calling the C<reticulate> routine will be equivalent to: Spliner->new->gather_data->analyze(detail => 100)->results; If any method returns something on which methods may not be called, the routine croaks. The arguments to C<curry_chain> form an optlist. The names are methods to be called and the arguments, if given, are arrayrefs to be dereferenced and passed as arguments to those methods. C<curry_chain> returns a generator like those expected by Sub::Exporter. B<Achtung!> at present, there is no way to pass arguments from the generated routine to the method calls. This will probably be solved in future revisions by allowing the opt list's values to be subroutines that will be called with the generated routine's stack. =head2 merge_col exports => { merge_col(defaults => { twiddle => \'_twiddle_gen', tweak => \&_tweak_gen, }), } This utility wraps the given generator in one that will merge the named collection into its args before calling it. This means that you can support a "default" collector in multiple exports without writing the code each time. You can specify as many pairs of collection names and generators as you like. =head2 mixin_installer use Sub::Exporter -setup => { installer => Sub::Exporter::Util::mixin_installer, exports => [ qw(foo bar baz) ], }; This utility returns an installer that will install into a superclass and adjust the ISA importing class to include the newly generated superclass. If the target of importing is an object, the hierarchy is reversed: the new class will be ISA the object's class, and the object will be reblessed. B<Prerequisites>: This utility requires that Package::Generator be installed. =head2 like It's a collector that adds imports for anything like given regex. If you provide this configuration: exports => [ qw(igrep imap islurp exhausted) ], collectors => { -like => Sub::Exporter::Util::like }, A user may import from your module like this: use Your::Iterator -like => qr/^i/; # imports igre, imap, islurp or use Your::Iterator -like => [ qr/^i/ => { -prefix => 'your_' } ]; The group-like prefix and suffix arguments are respected; other arguments are passed on to the generators for matching exports. =head1 AUTHOR Ricardo Signes <rjbs@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2007 by Ricardo Signes. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Exporter/Tutorial.pod 0000644 00000021666 15154224274 0010704 0 ustar 00 # PODNAME: Sub::Exporter::Tutorial # ABSTRACT: a friendly guide to exporting with Sub::Exporter __END__ =pod =head1 NAME Sub::Exporter::Tutorial - a friendly guide to exporting with Sub::Exporter =head1 VERSION version 0.987 =head1 DESCRIPTION =head2 What's an Exporter? When you C<use> a module, first it is required, then its C<import> method is called. The Perl documentation tells us that the following two lines are equivalent: use Module LIST; BEGIN { require Module; Module->import(LIST); } The method named C<import> is the module's I<exporter>, it exports functions and variables into its caller's namespace. =head2 The Basics of Sub::Exporter Sub::Exporter builds a custom exporter which can then be installed into your module. It builds this method based on configuration passed to its C<setup_exporter> method. A very basic use case might look like this: package Addition; use Sub::Exporter; Sub::Exporter::setup_exporter({ exports => [ qw(plus) ]}); sub plus { my ($x, $y) = @_; return $x + $y; } This would mean that when someone used your Addition module, they could have its C<plus> routine imported into their package: use Addition qw(plus); my $z = plus(2, 2); # this works, because now plus is in the main package That syntax to set up the exporter, above, is a little verbose, so for the simple case of just naming some exports, you can write this: use Sub::Exporter -setup => { exports => [ qw(plus) ] }; ...which is the same as the original example -- except that now the exporter is built and installed at compile time. Well, that and you typed less. =head2 Using Export Groups You can specify whole groups of things that should be exportable together. These are called groups. L<Exporter> calls these tags. To specify groups, you just pass a C<groups> key in your exporter configuration: package Food; use Sub::Exporter -setup => { exports => [ qw(apple banana beef fluff lox rabbit) ], groups => { fauna => [ qw(beef lox rabbit) ], flora => [ qw(apple banana) ], } }; Now, to import all that delicious foreign meat, your consumer needs only to write: use Food qw(:fauna); use Food qw(-fauna); Either one of the above is acceptable. A colon is more traditional, but barewords with a leading colon can't be enquoted by a fat arrow. We'll see why that matters later on. Groups can contain other groups. If you include a group name (with the leading dash or colon) in a group definition, it will be expanded recursively when the exporter is called. The exporter will B<not> recurse into the same group twice while expanding groups. There are two special groups: C<all> and C<default>. The C<all> group is defined for you and contains all exportable subs. You can redefine it, if you want to export only a subset when all exports are requested. The C<default> group is the set of routines to export when nothing specific is requested. By default, there is no C<default> group. =head2 Renaming Your Imports Sometimes you want to import something, but you don't like the name as which it's imported. Sub::Exporter can rename your imports for you. If you wanted to import C<lox> from the Food package, but you don't like the name, you could write this: use Food lox => { -as => 'salmon' }; Now you'd get the C<lox> routine, but it would be called salmon in your package. You can also rename entire groups by using the C<prefix> option: use Food -fauna => { -prefix => 'cute_little_' }; Now you can call your C<cute_little_rabbit> routine. (You can also call C<cute_little_beef>, but that hardly seems as enticing.) When you define groups, you can include renaming. use Sub::Exporter -setup => { exports => [ qw(apple banana beef fluff lox rabbit) ], groups => { fauna => [ qw(beef lox), rabbit => { -as => 'coney' } ], } }; A prefix on a group like that does the right thing. This is when it's useful to use a dash instead of a colon to indicate a group: you can put a fat arrow between the group and its arguments, then. use Food -fauna => { -prefix => 'lovely_' }; eat( lovely_coney ); # this works Prefixes also apply recursively. That means that this code works: use Sub::Exporter -setup => { exports => [ qw(apple banana beef fluff lox rabbit) ], groups => { fauna => [ qw(beef lox), rabbit => { -as => 'coney' } ], allowed => [ -fauna => { -prefix => 'willing_' }, 'banana' ], } }; ... use Food -allowed => { -prefix => 'any_' }; $dinner = any_willing_coney; # yum! Groups can also be passed a C<-suffix> argument. Finally, if the C<-as> argument to an exported routine is a reference to a scalar, a reference to the routine will be placed in that scalar. =head2 Building Subroutines to Order Sometimes, you want to export things that you don't have on hand. You might want to offer customized routines built to the specification of your consumer; that's just good business! With Sub::Exporter, this is easy. To offer subroutines to order, you need to provide a generator when you set up your exporter. A generator is just a routine that returns a new routine. L<perlref> is talking about these when it discusses closures and function templates. The canonical example of a generator builds a unique incrementor; here's how you'd do that with Sub::Exporter; package Package::Counter; use Sub::Exporter -setup => { exports => [ counter => sub { my $i = 0; sub { $i++ } } ], groups => { default => [ qw(counter) ] }, }; Now anyone can use your Package::Counter module and he'll receive a C<counter> in his package. It will count up by one, and will never interfere with anyone else's counter. This isn't very useful, though, unless the consumer can explain what he wants. This is done, in part, by supplying arguments when importing. The following example shows how a generator can take and use arguments: package Package::Counter; sub _build_counter { my ($class, $name, $arg) = @_; $arg ||= {}; my $i = $arg->{start} || 0; return sub { $i++ }; } use Sub::Exporter -setup => { exports => [ counter => \'_build_counter' ], groups => { default => [ qw(counter) ] }, }; Now, the consumer can (if he wants) specify a starting value for his counter: use Package::Counter counter => { start => 10 }; Arguments to a group are passed along to the generators of routines in that group, but Sub::Exporter arguments -- anything beginning with a dash -- are never passed in. When groups are nested, the arguments are merged as the groups are expanded. Notice, too, that in the example above, we gave a reference to a method I<name> rather than a method I<implementation>. By giving the name rather than the subroutine, we make it possible for subclasses of our "Package::Counter" module to replace the C<_build_counter> method. When a generator is called, it is passed four parameters: =over =item * the invocant on which the exporter was called =item * the name of the export being generated (not the name it's being installed as) =item * the arguments supplied for the routine =item * the collection of generic arguments =back The fourth item is the last major feature that hasn't been covered. =head2 Argument Collectors Sometimes you will want to accept arguments once that can then be available to any subroutine that you're going to export. To do this, you specify collectors, like this: package Menu::Airline use Sub::Exporter -setup => { exports => ... , groups => ... , collectors => [ qw(allergies ethics) ], }; Collectors look like normal exports in the import call, but they don't do anything but collect data which can later be passed to generators. If the module was used like this: use Menu::Airline allergies => [ qw(peanuts) ], ethics => [ qw(vegan) ]; ...the consumer would get a salad. Also, all the generators would be passed, as their fourth argument, something like this: { allerges => [ qw(peanuts) ], ethics => [ qw(vegan) ] } Generators may have arguments in their definition, as well. These must be code refs that perform validation of the collected values. They are passed the collection value and may return true or false. If they return false, the exporter will throw an exception. =head2 Generating Many Routines in One Scope Sometimes it's useful to have multiple routines generated in one scope. This way they can share lexical data which is otherwise unavailable. To do this, you can supply a generator for a group which returns a hashref of names and code references. This generator is passed all the usual data, and the group may receive the usual C<-prefix> or C<-suffix> arguments. =head1 SEE ALSO =over 4 =item * L<Sub::Exporter> for complete documentation and references to other exporters =back =head1 AUTHOR Ricardo Signes <rjbs@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2007 by Ricardo Signes. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Exporter/Cookbook.pod 0000644 00000020630 15154224275 0010636 0 ustar 00 # ABSTRACT: useful, demonstrative, or stupid Sub::Exporter tricks # PODNAME: Sub::Exporter::Cookbook __END__ =pod =head1 NAME Sub::Exporter::Cookbook - useful, demonstrative, or stupid Sub::Exporter tricks =head1 VERSION version 0.987 =head1 OVERVIEW Sub::Exporter is a fairly simple tool, and can be used to achieve some very simple goals. Its basic behaviors and their basic application (that is, "traditional" exporting of routines) are described in L<Sub::Exporter::Tutorial> and L<Sub::Exporter>. This document presents applications that may not be immediately obvious, or that can demonstrate how certain features can be put to use (for good or evil). =head1 THE RECIPES =head2 Exporting Methods as Routines With Exporter.pm, exporting methods is a non-starter. Sub::Exporter makes it simple. By using the C<curry_method> utility provided in L<Sub::Exporter::Util>, a method can be exported with the invocant built in. package Object::Strenuous; use Sub::Exporter::Util 'curry_method'; use Sub::Exporter -setup => { exports => [ objection => curry_method('new') ], }; With this configuration, the importing code may contain: my $obj = objection("irrelevant"); ...and this will be equivalent to: my $obj = Object::Strenuous->new("irrelevant"); The built-in invocant is determined by the invocant for the C<import> method. That means that if we were to subclass Object::Strenuous as follows: package Object::Strenuous::Repeated; @ISA = 'Object::Strenuous'; ...then importing C<objection> from the subclass would build-in that subclass. Finally, since the invocant can be an object, you can write something like this: package Cypher; use Sub::Exporter::Util 'curry_method'; use Sub::Exporter -setup => { exports => [ encypher => curry_method ], }; with the expectation that C<import> will be called on an instantiated Cypher object: BEGIN { my $cypher = Cypher->new( ... ); $cypher->import('encypher'); } Now there is a globally-available C<encypher> routine which calls the encypher method on an otherwise unavailable Cypher object. =head2 Exporting Methods as Methods While exporting modules usually export subroutines to be called as subroutines, it's easy to use Sub::Exporter to export subroutines meant to be called as methods on the importing package or its objects. Here's a trivial (and naive) example: package Mixin::DumpObj; use Data::Dumper; use Sub::Exporter -setup => { exports => [ qw(dump) ] }; sub dump { my ($self) = @_; return Dumper($self); } When writing your own object class, you can then import C<dump> to be used as a method, called like so: $object->dump; By assuming that the importing class will provide a certain interface, a method-exporting module can be used as a simple plugin: package Number::Plugin::Upto; use Sub::Exporter -setup => { into => 'Number', exports => [ qw(upto) ], groups => [ default => [ qw(upto) ] ], }; sub upto { my ($self) = @_; return 1 .. abs($self->as_integer); } The C<into> line in the configuration says that this plugin will export, by default, into the Number package, not into the C<use>-ing package. It can be exported anyway, though, and will work as long as the destination provides an C<as_integer> method like the one it expects. To import it to a different destination, one can just write: use Number::Plugin::Upto { into => 'Quantity' }; =head2 Mixing-in Complex External Behavior When exporting methods to be used as methods (see above), one very powerful option is to export methods that are generated routines that maintain an enclosed reference to the exporting module. This allows a user to import a single method which is implemented in terms of a complete, well-structured package. Here is a very small example: package Data::Analyzer; use Sub::Exporter -setup => { exports => [ analyze => \'_generate_analyzer' ], }; sub _generate_analyzer { my ($mixin, $name, $arg, $col) = @_; return sub { my ($self) = @_; my $values = [ $self->values ]; my $analyzer = $mixin->new($values); $analyzer->perform_analysis; $analyzer->aggregate_results; return $analyzer->summary; }; } If imported by any package providing a C<values> method, this plugin will provide a single C<analyze> method that acts as a simple interface to a more complex set of behaviors. Even more importantly, because the C<$mixin> value will be the invocant on which the C<import> was actually called, one can subclass C<Data::Analyzer> and replace only individual pieces of the complex behavior, making it easy to write complex, subclassable toolkits with simple single points of entry for external interfaces. =head2 Exporting Constants While Sub::Exporter isn't in the constant-exporting business, it's easy to export constants by using one of its sister modules, Package::Generator. package Important::Constants; use Sub::Exporter -setup => { collectors => [ constants => \'_set_constants' ], }; sub _set_constants { my ($class, $value, $data) = @_; Package::Generator->assign_symbols( $data->{into}, [ MEANING_OF_LIFE => \42, ONE_TRUE_BASE => \13, FACTORS => [ 6, 9 ], ], ); return 1; } Then, someone can write: use Important::Constants 'constants'; print "The factors @FACTORS produce $MEANING_OF_LIFE in $ONE_TRUE_BASE."; (The constants must be exported via a collector, because they are effectively altering the importing class in a way other than installing subroutines.) =head2 Altering the Importer's @ISA It's trivial to make a collector that changes the inheritance of an importing package: use Sub::Exporter -setup => { collectors => { -base => \'_make_base' }, }; sub _make_base { my ($class, $value, $data) = @_; my $target = $data->{into}; push @{"$target\::ISA"}, $class; } Then, the user of your class can write: use Some::Class -base; and become a subclass. This can be quite useful in building, for example, a module that helps build plugins. We may want a few utilities imported, but we also want to inherit behavior from some base plugin class; package Framework::Util; use Sub::Exporter -setup => { exports => [ qw(log global_config) ], groups => [ _plugin => [ qw(log global_config) ] collectors => { '-plugin' => \'_become_plugin' }, }; sub _become_plugin { my ($class, $value, $data) = @_; my $target = $data->{into}; push @{"$target\::ISA"}, $class->plugin_base_class; push @{ $data->{import_args} }, '-_plugin'; } Now, you can write a plugin like this: package Framework::Plugin::AirFreshener; use Framework::Util -plugin; =head2 Eating Exporter.pm's Brain You probably shouldn't actually do this in production. It's offered more as a demonstration than a suggestion. sub exporter_upgrade { my ($pkg) = @_; my $new_pkg = "$pkg\::UsingSubExporter"; return $new_pkg if $new_pkg->isa($pkg); Sub::Exporter::setup_exporter({ as => 'import', into => $new_pkg, exports => [ @{"$pkg\::EXPORT_OK"} ], groups => { %{"$pkg\::EXPORT_TAG"}, default => [ @{"$pkg\::EXPORTS"} ], }, }); @{"$new_pkg\::ISA"} = $pkg; return $new_pkg; } This routine, given the name of an existing package configured to use Exporter.pm, returns the name of a new package with a Sub::Exporter-powered C<import> routine. This lets you import C<Toolkit::exported_sub> into the current package with the name C<foo> by writing: BEGIN { require Toolkit; exporter_upgrade('Toolkit')->import(exported_sub => { -as => 'foo' }) } If you're feeling particularly naughty, this routine could have been declared in the UNIVERSAL package, meaning you could write: BEGIN { require Toolkit; Toolkit->exporter_upgrade->import(exported_sub => { -as => 'foo' }) } The new package will have all the same exporter configuration as the original, but will support export and group renaming, including exporting into scalar references. Further, since Sub::Exporter uses C<can> to find the routine being exported, the new package may be subclassed and some of its exports replaced. =head1 AUTHOR Ricardo Signes <rjbs@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2007 by Ricardo Signes. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Exporter.pm 0000644 00000107065 15154224275 0006732 0 ustar 00 use 5.006; use strict; use warnings; package Sub::Exporter; { $Sub::Exporter::VERSION = '0.987'; } # ABSTRACT: a sophisticated exporter for custom-built routines use Carp (); use Data::OptList 0.100 (); use Params::Util 0.14 (); # _CODELIKE use Sub::Install 0.92 (); # Given a potential import name, this returns the group name -- if it's got a # group prefix. sub _group_name { my ($name) = @_; return if (index q{-:}, (substr $name, 0, 1)) == -1; return substr $name, 1; } # \@groups is a canonicalized opt list of exports and groups this returns # another canonicalized opt list with groups replaced with relevant exports. # \%seen is groups we've already expanded and can ignore. # \%merge is merged options from the group we're descending through. sub _expand_groups { my ($class, $config, $groups, $collection, $seen, $merge) = @_; $seen ||= {}; $merge ||= {}; my @groups = @$groups; for my $i (reverse 0 .. $#groups) { if (my $group_name = _group_name($groups[$i][0])) { my $seen = { %$seen }; # faux-dynamic scoping splice @groups, $i, 1, _expand_group($class, $config, $groups[$i], $collection, $seen, $merge); } else { # there's nothing to munge in this export's args next unless my %merge = %$merge; # we have things to merge in; do so my $prefix = (delete $merge{-prefix}) || ''; my $suffix = (delete $merge{-suffix}) || ''; if ( Params::Util::_CODELIKE($groups[$i][1]) ## no critic Private or Params::Util::_SCALAR0($groups[$i][1]) ## no critic Private ) { # this entry was build by a group generator $groups[$i][0] = $prefix . $groups[$i][0] . $suffix; } else { my $as = ref $groups[$i][1]{-as} ? $groups[$i][1]{-as} : $groups[$i][1]{-as} ? $prefix . $groups[$i][1]{-as} . $suffix : $prefix . $groups[$i][0] . $suffix; $groups[$i][1] = { %{ $groups[$i][1] }, %merge, -as => $as }; } } } return \@groups; } # \@group is a name/value pair from an opt list. sub _expand_group { my ($class, $config, $group, $collection, $seen, $merge) = @_; $merge ||= {}; my ($group_name, $group_arg) = @$group; $group_name = _group_name($group_name); Carp::croak qq(group "$group_name" is not exported by the $class module) unless exists $config->{groups}{$group_name}; return if $seen->{$group_name}++; if (ref $group_arg) { my $prefix = (delete $merge->{-prefix}||'') . ($group_arg->{-prefix}||''); my $suffix = ($group_arg->{-suffix}||'') . (delete $merge->{-suffix}||''); $merge = { %$merge, %$group_arg, ($prefix ? (-prefix => $prefix) : ()), ($suffix ? (-suffix => $suffix) : ()), }; } my $exports = $config->{groups}{$group_name}; if ( Params::Util::_CODELIKE($exports) ## no critic Private or Params::Util::_SCALAR0($exports) ## no critic Private ) { # I'm not very happy with this code for hiding -prefix and -suffix, but # it's needed, and I'm not sure, offhand, how to make it better. # -- rjbs, 2006-12-05 my $group_arg = $merge ? { %$merge } : {}; delete $group_arg->{-prefix}; delete $group_arg->{-suffix}; my $group = Params::Util::_CODELIKE($exports) ## no critic Private ? $exports->($class, $group_name, $group_arg, $collection) : $class->$$exports($group_name, $group_arg, $collection); Carp::croak qq(group generator "$group_name" did not return a hashref) if ref $group ne 'HASH'; my $stuff = [ map { [ $_ => $group->{$_} ] } keys %$group ]; return @{ _expand_groups($class, $config, $stuff, $collection, $seen, $merge) }; } else { $exports = Data::OptList::mkopt($exports, "$group_name exports"); return @{ _expand_groups($class, $config, $exports, $collection, $seen, $merge) }; } } sub _mk_collection_builder { my ($col, $etc) = @_; my ($config, $import_args, $class, $into) = @$etc; my %seen; sub { my ($collection) = @_; my ($name, $value) = @$collection; Carp::croak "collection $name provided multiple times in import" if $seen{ $name }++; if (ref(my $hook = $config->{collectors}{$name})) { my $arg = { name => $name, config => $config, import_args => $import_args, class => $class, into => $into, }; my $error_msg = "collection $name failed validation"; if (Params::Util::_SCALAR0($hook)) { ## no critic Private Carp::croak $error_msg unless $class->$$hook($value, $arg); } else { Carp::croak $error_msg unless $hook->($value, $arg); } } $col->{ $name } = $value; } } # Given a config and pre-canonicalized importer args, remove collections from # the args and return them. sub _collect_collections { my ($config, $import_args, $class, $into) = @_; my @collections = map { splice @$import_args, $_, 1 } grep { exists $config->{collectors}{ $import_args->[$_][0] } } reverse 0 .. $#$import_args; unshift @collections, [ INIT => {} ] if $config->{collectors}{INIT}; my $col = {}; my $builder = _mk_collection_builder($col, \@_); for my $collection (@collections) { $builder->($collection) } return $col; } sub setup_exporter { my ($config) = @_; Carp::croak 'into and into_level may not both be supplied to exporter' if exists $config->{into} and exists $config->{into_level}; my $as = delete $config->{as} || 'import'; my $into = exists $config->{into} ? delete $config->{into} : exists $config->{into_level} ? caller(delete $config->{into_level}) : caller(0); my $import = build_exporter($config); Sub::Install::reinstall_sub({ code => $import, into => $into, as => $as, }); } sub _key_intersection { my ($x, $y) = @_; my %seen = map { $_ => 1 } keys %$x; my @names = grep { $seen{$_} } keys %$y; } # Given the config passed to setup_exporter, which contains sugary opt list # data, rewrite the opt lists into hashes, catch a few kinds of invalid # configurations, and set up defaults. Since the config is a reference, it's # rewritten in place. my %valid_config_key; BEGIN { %valid_config_key = map { $_ => 1 } qw(as collectors installer generator exports groups into into_level), qw(exporter), # deprecated } sub _assert_collector_names_ok { my ($collectors) = @_; for my $reserved_name (grep { /\A[_A-Z]+\z/ } keys %$collectors) { Carp::croak "unknown reserved collector name: $reserved_name" if $reserved_name ne 'INIT'; } } sub _rewrite_build_config { my ($config) = @_; if (my @keys = grep { not exists $valid_config_key{$_} } keys %$config) { Carp::croak "unknown options (@keys) passed to Sub::Exporter"; } Carp::croak q(into and into_level may not both be supplied to exporter) if exists $config->{into} and exists $config->{into_level}; # XXX: Remove after deprecation period. if ($config->{exporter}) { Carp::cluck "'exporter' argument to build_exporter is deprecated. Use 'installer' instead; the semantics are identical."; $config->{installer} = delete $config->{exporter}; } Carp::croak q(into and into_level may not both be supplied to exporter) if exists $config->{into} and exists $config->{into_level}; for (qw(exports collectors)) { $config->{$_} = Data::OptList::mkopt_hash( $config->{$_}, $_, [ 'CODE', 'SCALAR' ], ); } _assert_collector_names_ok($config->{collectors}); if (my @names = _key_intersection(@$config{qw(exports collectors)})) { Carp::croak "names (@names) used in both collections and exports"; } $config->{groups} = Data::OptList::mkopt_hash( $config->{groups}, 'groups', [ 'HASH', # standard opt list 'ARRAY', # standard opt list 'CODE', # group generator 'SCALAR', # name of group generation method ] ); # by default, export nothing $config->{groups}{default} ||= []; # by default, build an all-inclusive 'all' group $config->{groups}{all} ||= [ keys %{ $config->{exports} } ]; $config->{generator} ||= \&default_generator; $config->{installer} ||= \&default_installer; } sub build_exporter { my ($config) = @_; _rewrite_build_config($config); my $import = sub { my ($class) = shift; # XXX: clean this up -- rjbs, 2006-03-16 my $special = (ref $_[0]) ? shift(@_) : {}; Carp::croak q(into and into_level may not both be supplied to exporter) if exists $special->{into} and exists $special->{into_level}; if ($special->{exporter}) { Carp::cluck "'exporter' special import argument is deprecated. Use 'installer' instead; the semantics are identical."; $special->{installer} = delete $special->{exporter}; } my $into = defined $special->{into} ? delete $special->{into} : defined $special->{into_level} ? caller(delete $special->{into_level}) : defined $config->{into} ? $config->{into} : defined $config->{into_level} ? caller($config->{into_level}) : caller(0); my $generator = delete $special->{generator} || $config->{generator}; my $installer = delete $special->{installer} || $config->{installer}; # this builds a AOA, where the inner arrays are [ name => value_ref ] my $import_args = Data::OptList::mkopt([ @_ ]); # is this right? defaults first or collectors first? -- rjbs, 2006-06-24 $import_args = [ [ -default => undef ] ] unless @$import_args; my $collection = _collect_collections($config, $import_args, $class, $into); my $to_import = _expand_groups($class, $config, $import_args, $collection); # now, finally $import_arg is really the "to do" list _do_import( { class => $class, col => $collection, config => $config, into => $into, generator => $generator, installer => $installer, }, $to_import, ); }; return $import; } sub _do_import { my ($arg, $to_import) = @_; my @todo; for my $pair (@$to_import) { my ($name, $import_arg) = @$pair; my ($generator, $as); if ($import_arg and Params::Util::_CODELIKE($import_arg)) { ## no critic # This is the case when a group generator has inserted name/code pairs. $generator = sub { $import_arg }; $as = $name; } else { $import_arg = { $import_arg ? %$import_arg : () }; Carp::croak qq("$name" is not exported by the $arg->{class} module) unless exists $arg->{config}{exports}{$name}; $generator = $arg->{config}{exports}{$name}; $as = exists $import_arg->{-as} ? (delete $import_arg->{-as}) : $name; } my $code = $arg->{generator}->( { class => $arg->{class}, name => $name, arg => $import_arg, col => $arg->{col}, generator => $generator, } ); push @todo, $as, $code; } $arg->{installer}->( { class => $arg->{class}, into => $arg->{into}, col => $arg->{col}, }, \@todo, ); } ## Cute idea, possibly for future use: also supply an "unimport" for: ## no Module::Whatever qw(arg arg arg); # sub _unexport { # my (undef, undef, undef, undef, undef, $as, $into) = @_; # # if (ref $as eq 'SCALAR') { # undef $$as; # } elsif (ref $as) { # Carp::croak "invalid reference type for $as: " . ref $as; # } else { # no strict 'refs'; # delete &{$into . '::' . $as}; # } # } sub default_generator { my ($arg) = @_; my ($class, $name, $generator) = @$arg{qw(class name generator)}; if (not defined $generator) { my $code = $class->can($name) or Carp::croak "can't locate exported subroutine $name via $class"; return $code; } # I considered making this "$class->$generator(" but it seems that # overloading precedence would turn an overloaded-as-code generator object # into a string before code. -- rjbs, 2006-06-11 return $generator->($class, $name, $arg->{arg}, $arg->{col}) if Params::Util::_CODELIKE($generator); ## no critic Private # This "must" be a scalar reference, to a generator method name. # -- rjbs, 2006-12-05 return $class->$$generator($name, $arg->{arg}, $arg->{col}); } sub default_installer { my ($arg, $to_export) = @_; for (my $i = 0; $i < @$to_export; $i += 2) { my ($as, $code) = @$to_export[ $i, $i+1 ]; # Allow as isa ARRAY to push onto an array? # Allow into isa HASH to install name=>code into hash? if (ref $as eq 'SCALAR') { $$as = $code; } elsif (ref $as) { Carp::croak "invalid reference type for $as: " . ref $as; } else { Sub::Install::reinstall_sub({ code => $code, into => $arg->{into}, as => $as }); } } } sub default_exporter { Carp::cluck "default_exporter is deprecated; call default_installer instead; the semantics are identical"; goto &default_installer; } setup_exporter({ exports => [ qw(setup_exporter build_exporter), _import => sub { build_exporter($_[2]) }, ], groups => { all => [ qw(setup_exporter build_export) ], }, collectors => { -setup => \&_setup }, }); sub _setup { my ($value, $arg) = @_; if (ref $value eq 'HASH') { push @{ $arg->{import_args} }, [ _import => { -as => 'import', %$value } ]; return 1; } elsif (ref $value eq 'ARRAY') { push @{ $arg->{import_args} }, [ _import => { -as => 'import', exports => $value } ]; return 1; } return; } "jn8:32"; # <-- magic true value __END__ =pod =head1 NAME Sub::Exporter - a sophisticated exporter for custom-built routines =head1 VERSION version 0.987 =head1 SYNOPSIS Sub::Exporter must be used in two places. First, in an exporting module: # in the exporting module: package Text::Tweaker; use Sub::Exporter -setup => { exports => [ qw(squish titlecase), # always works the same way reformat => \&build_reformatter, # generator to build exported function trim => \&build_trimmer, indent => \&build_indenter, ], collectors => [ 'defaults' ], }; Then, in an importing module: # in the importing module: use Text::Tweaker 'squish', indent => { margin => 5 }, reformat => { width => 79, justify => 'full', -as => 'prettify_text' }, defaults => { eol => 'CRLF' }; With this setup, the importing module ends up with three routines: C<squish>, C<indent>, and C<prettify_text>. The latter two have been built to the specifications of the importer -- they are not just copies of the code in the exporting package. =head1 DESCRIPTION B<ACHTUNG!> If you're not familiar with Exporter or exporting, read L<Sub::Exporter::Tutorial> first! =head2 Why Generators? The biggest benefit of Sub::Exporter over existing exporters (including the ubiquitous Exporter.pm) is its ability to build new coderefs for export, rather than to simply export code identical to that found in the exporting package. If your module's consumers get a routine that works like this: use Data::Analyze qw(analyze); my $value = analyze($data, $tolerance, $passes); and they constantly pass only one or two different set of values for the non-C<$data> arguments, your code can benefit from Sub::Exporter. By writing a simple generator, you can let them do this, instead: use Data::Analyze analyze => { tolerance => 0.10, passes => 10, -as => analyze10 }, analyze => { tolerance => 0.15, passes => 50, -as => analyze50 }; my $value = analyze10($data); The package with the generator for that would look something like this: package Data::Analyze; use Sub::Exporter -setup => { exports => [ analyze => \&build_analyzer, ], }; sub build_analyzer { my ($class, $name, $arg) = @_; return sub { my $data = shift; my $tolerance = shift || $arg->{tolerance}; my $passes = shift || $arg->{passes}; analyze($data, $tolerance, $passes); } } Your module's user now has to do less work to benefit from it -- and remember, you're often your own user! Investing in customized subroutines is an investment in future laziness. This also avoids a common form of ugliness seen in many modules: package-level configuration. That is, you might have seen something like the above implemented like so: use Data::Analyze qw(analyze); $Data::Analyze::default_tolerance = 0.10; $Data::Analyze::default_passes = 10; This might save time, until you have multiple modules using Data::Analyze. Because there is only one global configuration, they step on each other's toes and your code begins to have mysterious errors. Generators can also allow you to export class methods to be called as subroutines: package Data::Methodical; use Sub::Exporter -setup => { exports => { some_method => \&_curry_class } }; sub _curry_class { my ($class, $name) = @_; sub { $class->$name(@_); }; } Because of the way that exporters and Sub::Exporter work, any package that inherits from Data::Methodical can inherit its exporter and override its C<some_method>. If a user imports C<some_method> from that package, he'll receive a subroutine that calls the method on the subclass, rather than on Data::Methodical itself. =head2 Other Customizations Building custom routines with generators isn't the only way that Sub::Exporters allows the importing code to refine its use of the exported routines. They may also be renamed to avoid naming collisions. Consider the following code: # this program determines to which circle of Hell you will be condemned use Morality qw(sin virtue); # for calculating viciousness use Math::Trig qw(:all); # for dealing with circles The programmer has inadvertently imported two C<sin> routines. The solution, in Exporter.pm-based modules, would be to import only one and then call the other by its fully-qualified name. Alternately, the importer could write a routine that did so, or could mess about with typeglobs. How much easier to write: # this program determines to which circle of Hell you will be condemned use Morality qw(virtue), sin => { -as => 'offense' }; use Math::Trig -all => { -prefix => 'trig_' }; and to have at one's disposal C<offense> and C<trig_sin> -- not to mention C<trig_cos> and C<trig_tan>. =head1 EXPORTER CONFIGURATION You can configure an exporter for your package by using Sub::Exporter like so: package Tools; use Sub::Exporter -setup => { exports => [ qw(function1 function2 function3) ] }; This is the simplest way to use the exporter, and is basically equivalent to this: package Tools; use base qw(Exporter); our @EXPORT_OK = qw(function1 function2 function3); Any basic use of Sub::Exporter will look like this: package Tools; use Sub::Exporter -setup => \%config; The following keys are valid in C<%config>: exports - a list of routines to provide for exporting; each routine may be followed by generator groups - a list of groups to provide for exporting; each must be followed by either (a) a list of exports, possibly with arguments for each export, or (b) a generator collectors - a list of names into which values are collected for use in routine generation; each name may be followed by a validator In addition to the basic options above, a few more advanced options may be passed: into_level - how far up the caller stack to look for a target (default 0) into - an explicit target (package) into which to export routines In other words: Sub::Exporter installs a C<import> routine which, when called, exports routines to the calling namespace. The C<into> and C<into_level> options change where those exported routines are installed. generator - a callback used to produce the code that will be installed default: Sub::Exporter::default_generator installer - a callback used to install the code produced by the generator default: Sub::Exporter::default_installer For information on how these callbacks are used, see the documentation for C<L</default_generator>> and C<L</default_installer>>. =head2 Export Configuration The C<exports> list may be provided as an array reference or a hash reference. The list is processed in such a way that the following are equivalent: { exports => [ qw(foo bar baz), quux => \&quux_generator ] } { exports => { foo => undef, bar => undef, baz => undef, quux => \&quux_generator } } Generators are code that return coderefs. They are called with four parameters: $class - the class whose exporter has been called (the exporting class) $name - the name of the export for which the routine is being build \%arg - the arguments passed for this export \%col - the collections for this import Given the configuration in the L</SYNOPSIS>, the following C<use> statement: use Text::Tweaker reformat => { -as => 'make_narrow', width => 33 }, defaults => { eol => 'CR' }; would result in the following call to C<&build_reformatter>: my $code = build_reformatter( 'Text::Tweaker', 'reformat', { width => 33 }, # note that -as is not passed in { defaults => { eol => 'CR' } }, ); The returned coderef (C<$code>) would then be installed as C<make_narrow> in the calling package. Instead of providing a coderef in the configuration, a reference to a method name may be provided. This method will then be called on the invocant of the C<import> method. (In this case, we do not pass the C<$class> parameter, as it would be redundant.) =head2 Group Configuration The C<groups> list can be passed in the same forms as C<exports>. Groups must have values to be meaningful, which may either list exports that make up the group (optionally with arguments) or may provide a way to build the group. The simpler case is the first: a group definition is a list of exports. Here's the example that could go in exporter in the L</SYNOPSIS>. groups => { default => [ qw(reformat) ], shorteners => [ qw(squish trim) ], email_safe => [ 'indent', reformat => { -as => 'email_format', width => 72 } ], }, Groups are imported by specifying their name prefixed be either a dash or a colon. This line of code would import the C<shorteners> group: use Text::Tweaker qw(-shorteners); Arguments passed to a group when importing are merged into the groups options and passed to any relevant generators. Groups can contain other groups, but looping group structures are ignored. The other possible value for a group definition, a coderef, allows one generator to build several exportable routines simultaneously. This is useful when many routines must share enclosed lexical variables. The coderef must return a hash reference. The keys will be used as export names and the values are the subs that will be exported. This example shows a simple use of the group generator. package Data::Crypto; use Sub::Exporter -setup => { groups => { cipher => \&build_cipher_group } }; sub build_cipher_group { my ($class, $group, $arg) = @_; my ($encode, $decode) = build_codec($arg->{secret}); return { cipher => $encode, decipher => $decode }; } The C<cipher> and C<decipher> routines are built in a group because they are built together by code which encloses their secret in their environment. =head3 Default Groups If a module that uses Sub::Exporter is C<use>d with no arguments, it will try to export the group named C<default>. If that group has not been specifically configured, it will be empty, and nothing will happen. Another group is also created if not defined: C<all>. The C<all> group contains all the exports from the exports list. =head2 Collector Configuration The C<collectors> entry in the exporter configuration gives names which, when found in the import call, have their values collected and passed to every generator. For example, the C<build_analyzer> generator that we saw above could be rewritten as: sub build_analyzer { my ($class, $name, $arg, $col) = @_; return sub { my $data = shift; my $tolerance = shift || $arg->{tolerance} || $col->{defaults}{tolerance}; my $passes = shift || $arg->{passes} || $col->{defaults}{passes}; analyze($data, $tolerance, $passes); } } That would allow the importer to specify global defaults for his imports: use Data::Analyze 'analyze', analyze => { tolerance => 0.10, -as => analyze10 }, analyze => { tolerance => 0.15, passes => 50, -as => analyze50 }, defaults => { passes => 10 }; my $A = analyze10($data); # equivalent to analyze($data, 0.10, 10); my $C = analyze50($data); # equivalent to analyze($data, 0.15, 50); my $B = analyze($data, 0.20); # equivalent to analyze($data, 0.20, 10); If values are provided in the C<collectors> list during exporter setup, they must be code references, and are used to validate the importer's values. The validator is called when the collection is found, and if it returns false, an exception is thrown. We could ensure that no one tries to set a global data default easily: collectors => { defaults => sub { return (exists $_[0]->{data}) ? 0 : 1 } } Collector coderefs can also be used as hooks to perform arbitrary actions before anything is exported. When the coderef is called, it is passed the value of the collection and a hashref containing the following entries: name - the name of the collector config - the exporter configuration (hashref) import_args - the arguments passed to the exporter, sans collections (aref) class - the package on which the importer was called into - the package into which exports will be exported Collectors with all-caps names (that is, made up of underscore or capital A through Z) are reserved for special use. The only currently implemented special collector is C<INIT>, whose hook (if present in the exporter configuration) is always run before any other hook. =head1 CALLING THE EXPORTER Arguments to the exporter (that is, the arguments after the module name in a C<use> statement) are parsed as follows: First, the collectors gather any collections found in the arguments. Any reference type may be given as the value for a collector. For each collection given in the arguments, its validator (if any) is called. Next, groups are expanded. If the group is implemented by a group generator, the generator is called. There are two special arguments which, if given to a group, have special meaning: -prefix - a string to prepend to any export imported from this group -suffix - a string to append to any export imported from this group Finally, individual export generators are called and all subs, generated or otherwise, are installed in the calling package. There is only one special argument for export generators: -as - where to install the exported sub Normally, C<-as> will contain an alternate name for the routine. It may, however, contain a reference to a scalar. If that is the case, a reference the generated routine will be placed in the scalar referenced by C<-as>. It will not be installed into the calling package. =head2 Special Exporter Arguments The generated exporter accept some special options, which may be passed as the first argument, in a hashref. These options are: into_level into generator installer These override the same-named configuration options described in L</EXPORTER CONFIGURATION>. =head1 SUBROUTINES =head2 setup_exporter This routine builds and installs an C<import> routine. It is called with one argument, a hashref containing the exporter configuration. Using this, it builds an exporter and installs it into the calling package with the name "import." In addition to the normal exporter configuration, a few named arguments may be passed in the hashref: into - into what package should the exporter be installed into_level - into what level up the stack should the exporter be installed as - what name should the installed exporter be given By default the exporter is installed with the name C<import> into the immediate caller of C<setup_exporter>. In other words, if your package calls C<setup_exporter> without providing any of the three above arguments, it will have an C<import> routine installed. Providing both C<into> and C<into_level> will cause an exception to be thrown. The exporter is built by C<L</build_exporter>>. =head2 build_exporter Given a standard exporter configuration, this routine builds and returns an exporter -- that is, a subroutine that can be installed as a class method to perform exporting on request. Usually, this method is called by C<L</setup_exporter>>, which then installs the exporter as a package's import routine. =head2 default_generator This is Sub::Exporter's default generator. It takes bits of configuration that have been gathered during the import and turns them into a coderef that can be installed. my $code = default_generator(\%arg); Passed arguments are: class - the class on which the import method was called name - the name of the export being generated arg - the arguments to the generator col - the collections generator - the generator to be used to build the export (code or scalar ref) =head2 default_installer This is Sub::Exporter's default installer. It does what Sub::Exporter promises: it installs code into the target package. default_installer(\%arg, \@to_export); Passed arguments are: into - the package into which exports should be delivered C<@to_export> is a list of name/value pairs. The default exporter assigns code (the values) to named slots (the names) in the given package. If the name is a scalar reference, the scalar reference is made to point to the code reference instead. =head1 EXPORTS Sub::Exporter also offers its own exports: the C<setup_exporter> and C<build_exporter> routines described above. It also provides a special "setup" collector, which will set up an exporter using the parameters passed to it. Note that the "setup" collector (seen in examples like the L</SYNOPSIS> above) uses C<build_exporter>, not C<setup_exporter>. This means that the special arguments like "into" and "as" for C<setup_exporter> are not accepted here. Instead, you may write something like: use Sub::Exporter { into => 'Target::Package' }, -setup => { -as => 'do_import', exports => [ ... ], } ; Finding a good reason for wanting to do this is left as an exercise for the reader. =head1 COMPARISONS There are a whole mess of exporters on the CPAN. The features included in Sub::Exporter set it apart from any existing Exporter. Here's a summary of some other exporters and how they compare. =over =item * L<Exporter> and co. This is the standard Perl exporter. Its interface is a little clunky, but it's fast and ubiquitous. It can do some things that Sub::Exporter can't: it can export things other than routines, it can import "everything in this group except this symbol," and some other more esoteric things. These features seem to go nearly entirely unused. It always exports things exactly as they appear in the exporting module; it can't rename or customize routines. Its groups ("tags") can't be nested. L<Exporter::Lite> is a whole lot like Exporter, but it does significantly less: it supports exporting symbols, but not groups, pattern matching, or negation. The fact that Sub::Exporter can't export symbols other than subroutines is a good idea, not a missing feature. For simple uses, setting up Sub::Exporter is about as easy as Exporter. For complex uses, Sub::Exporter makes hard things possible, which would not be possible with Exporter. When using a module that uses Sub::Exporter, users familiar with Exporter will probably see no difference in the basics. These two lines do about the same thing in whether the exporting module uses Exporter or Sub::Exporter. use Some::Module qw(foo bar baz); use Some::Module qw(foo :bar baz); The definition for exporting in Exporter.pm might look like this: package Some::Module; use base qw(Exporter); our @EXPORT_OK = qw(foo bar baz quux); our %EXPORT_TAGS = (bar => [ qw(bar baz) ]); Using Sub::Exporter, it would look like this: package Some::Module; use Sub::Exporter -setup => { exports => [ qw(foo bar baz quux) ], groups => { bar => [ qw(bar baz) ]} }; Sub::Exporter respects inheritance, so that a package may export inherited routines, and will export the most inherited version. Exporting methods without currying away the invocant is a bad idea, but Sub::Exporter allows you to do just that -- and anyway, there are other uses for this feature, like packages of exported subroutines which use inheritance specifically to allow more specialized, but similar, packages. L<Exporter::Easy> provides a wrapper around the standard Exporter. It makes it simpler to build groups, but doesn't provide any more functionality. Because it is a front-end to Exporter, it will store your exporter's configuration in global package variables. =item * Attribute-Based Exporters Some exporters use attributes to mark variables to export. L<Exporter::Simple> supports exporting any kind of symbol, and supports groups. Using a module like Exporter or Sub::Exporter, it's easy to look at one place and see what is exported, but it's impossible to look at a variable definition and see whether it is exported by that alone. Exporter::Simple makes this trade in reverse: each variable's declaration includes its export definition, but there is no one place to look to find a manifest of exports. More importantly, Exporter::Simple does not add any new features to those of Exporter. In fact, like Exporter::Easy, it is just a front-end to Exporter, so it ends up storing its configuration in global package variables. (This means that there is one place to look for your exporter's manifest, actually. You can inspect the C<@EXPORT> package variables, and other related package variables, at runtime.) L<Perl6::Export> isn't actually attribute based, but looks similar. Its syntax is borrowed from Perl 6, and implemented by a source filter. It is a prototype of an interface that is still being designed. It should probably be avoided for production work. On the other hand, L<Perl6::Export::Attrs> implements Perl 6-like exporting, but translates it into Perl 5 by providing attributes. =item * Other Exporters L<Exporter::Renaming> wraps the standard Exporter to allow it to export symbols with changed names. L<Class::Exporter> performs a special kind of routine generation, giving each importing package an instance of your class, and then exporting the instance's methods as normal routines. (Sub::Exporter, of course, can easily emulate this behavior, as shown above.) L<Exporter::Tidy> implements a form of renaming (using its C<_map> argument) and of prefixing, and implements groups. It also avoids using package variables for its configuration. =back =head1 TODO =over =item * write a set of longer, more demonstrative examples =item * solidify the "custom exporter" interface (see C<&default_exporter>) =item * add an "always" group =back =head1 THANKS Hans Dieter Pearcey provided helpful advice while I was writing Sub::Exporter. Ian Langworth and Shawn Sorichetti asked some good questions and helped me improve my documentation quite a bit. Yuval Kogman helped me find a bunch of little problems. Thanks, guys! =head1 BUGS Please report any bugs or feature requests through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 AUTHOR Ricardo Signes <rjbs@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2007 by Ricardo Signes. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut