Sub::Exporter::Tutorial 0.970 review

by on

Sub::Exporter::Tutorial is a friendly guide to exporting with Sub::Exporter. What's an Exporter? When you use a module, first i

License: Perl Artistic License
File size: 34K
Developer: Ricardo SIGNES
0 stars award from

Sub::Exporter::Tutorial is a friendly guide to exporting with Sub::Exporter.

What's an Exporter?

When you use a module, first it is required, then its 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 import method is the module's exporter.

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

Using Export Groups

You can specify whole groups of things that should be exportable together. These are called groups. Exporter calls these tags. To specify groups, you just pass a 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 not recurse into the same group twice while expanding groups.

There are two special groups: all and default. The all group is defined by default, and contains all exportable subs. You can redefine it, if you want to export only a subset when all exports are requested. The default group is the set of routines to export when nothing specific is requested. By default, there is no default group.


Sub::Exporter::Tutorial 0.970 keywords