perldoc > Sub::Exporter

πŸ“– NAME

Sub::Exporter β€” a sophisticated exporter for custom-built routines

πŸš€ Quick Reference

Use CaseCommandDescription
Basic setupuse Sub::Exporter -setup => { exports => [qw(foo bar)] };Create an exporter with simple function list
Export with generatoruse Sub::Exporter -setup => { exports => [analyze => \&build_analyzer] };Build custom routines per import call
Rename importuse Text::Tweaker reformat => { -as => 'prettify' };Import a function under a different name
Use group (prefix)use Math::Trig -all => { -prefix => 'trig_' };Import all functions with a prefix
Collect global defaultsuse Data::Analyze defaults => { passes => 10 };Pass shared configuration to all generators
Group generatorgroups => { cipher => \&build_cipher_group }Generate multiple related exports together

πŸ“¦ VERSION

version 0.988

πŸ“‹ 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: squish, indent, and 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.

πŸ“ DESCRIPTION

ACHTUNG! If you're not familiar with Exporter or exporting, read Sub::Exporter::Tutorial first!

πŸ”§ 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-$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 some_method. If a user imports some_method from that package, he'll receive a subroutine that calls the method on the subclass, rather than on Data::Methodical itself. Keep in mind that if you re-setup Sub::Exporter in a package that inherits from Data::Methodical you will, of course, be entirely replacing the exporter from Data::Methodical. import is a method, and is hidden by the same means as any other method.

πŸ”§ 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 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 offense and trig_sin β€” not to mention trig_cos and trig_tan.

🐧 PERL VERSION SUPPORT

This module has a long-term perl support period. That means it will not require a version of perl released fewer than five years ago.

Although it may work on older versions of perl, no guarantee is made that the minimum required version will not be increased. The version may be increased for any reason, and there is no promise that patches will be accepted to lower the minimum required perl.

βš™οΈ 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 %config:

In addition to the basic options above, a few more advanced options may be passed:

In other words: Sub::Exporter installs an import routine which, when called, exports routines to the calling namespace. The into and into_level options change where those exported routines are installed.

For information on how these callbacks are used, see the documentation for default_generator and default_installer.

πŸ“¦ Export Configuration

The 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:

Given the configuration in the SYNOPSIS, the following use statement:

use Text::Tweaker
  reformat => { -as => 'make_narrow', width => 33 },
  defaults => { eol => 'CR' };

…would result in the following call to &build_reformatter:

my $code = build_reformatter(
  'Text::Tweaker',
  'reformat',
  { width => 33 }, # note that -as is not passed in
  { defaults => { eol => 'CR' } },
);

The returned coderef ($code) would then be installed as 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 import method. (In this case, we do not pass the $class parameter, as it would be redundant.)

πŸ“‚ Group Configuration

The groups list can be passed in the same forms as 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 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 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 cipher and decipher routines are built in a group because they are built together by code which encloses their secret in their environment.

Default Groups

If a module that uses Sub::Exporter is used with no arguments, it will try to export the group named 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: all. The all group contains all the exports from the exports list.

πŸ“¦ Collector Configuration

The 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 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 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:

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 INIT, whose hook (if present in the exporter configuration) is always run before any other hook.

πŸ“ž CALLING THE EXPORTER

Arguments to the exporter (that is, the arguments after the module name in a 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:

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:

Normally, -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 -as. It will not be installed into the calling package.

⚑ Special Exporter Arguments

The generated exporter accept some special options, which may be passed as the first argument, in a hashref.

These options are:

These override the same-named configuration options described in EXPORTER CONFIGURATION.

πŸ”§ SUBROUTINES

setup_exporter

This routine builds and installs an 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:

By default the exporter is installed with the name import into the immediate caller of setup_exporter. In other words, if your package calls setup_exporter without providing any of the three above arguments, it will have an import routine installed.

Providing both into and into_level will cause an exception to be thrown.

The exporter is built by build_exporter.

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 setup_exporter, which then installs the exporter as a package's import routine.

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:

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:

@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.

πŸ“€ EXPORTS

Sub::Exporter also offers its own exports: the setup_exporter and 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 SYNOPSIS above) uses build_exporter, not setup_exporter. This means that the special arguments like into and as for 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.

πŸ” 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.

πŸ“‹ TODO

πŸ™ 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, friends!

πŸ› BUGS

Please report any bugs or feature requests through the web interface at http://rt.cpan.org. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

πŸ‘€ AUTHOR

Ricardo Signes <rjbs AT semiotic.systems>

πŸ‘₯ CONTRIBUTORS

πŸ“„ 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.

Sub::Exporter
πŸ“– NAME πŸš€ Quick Reference πŸ“¦ VERSION πŸ“‹ SYNOPSIS πŸ“ DESCRIPTION
πŸ”§ Why Generators? πŸ”§ Other Customizations
🐧 PERL VERSION SUPPORT βš™οΈ EXPORTER CONFIGURATION
πŸ“¦ Export Configuration πŸ“‚ Group Configuration πŸ“¦ Collector Configuration
πŸ“ž CALLING THE EXPORTER
⚑ Special Exporter Arguments
πŸ”§ SUBROUTINES
setup_exporter build_exporter default_generator default_installer
πŸ“€ EXPORTS πŸ” COMPARISONS πŸ“‹ TODO πŸ™ THANKS πŸ› BUGS πŸ‘€ AUTHOR πŸ‘₯ CONTRIBUTORS πŸ“„ COPYRIGHT AND LICENSE

Generated by phpman v4.9.26-5-g7740029 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-15 06:51 @216.73.216.208
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!

^_top_^