Sub::Ex...Tutorial(3)

πŸ’– Sub::Exporter::Tutorial β€” a friendly guide to exporting with Sub::Exporter πŸ’–

okay so bestie, this is Sub::Exporter::Tutorial, from the User Contributed Perl Documentation crew. it's the friendly-guide era of the docs and honestly? iconic. let's get into it πŸ¦‹


✨ VERSION ✨

version 0.991 β€” periodt, that's the one we're reading πŸ’…


🌸 DESCRIPTION 🌸

πŸŽ€ What's an Exporter?

so like, when you use a module, two things happen in order: first it gets required, then its import method gets called. the Perl docs literally tell us these two lines are the same thing:

use Module LIST;

BEGIN { require Module; Module->import(LIST); }

the method named import is the module's exporter β€” that's the whole vibe. it exports functions and variables into its caller's namespace. it's giving delivery service for subs 🫢


🌈 The Basics of Sub::Exporter

Sub::Exporter builds a custom exporter, and then you install that bad boy into your module. it builds the method based on configuration you pass to its setup_exporter method.

a very basic use case, lowkey the starter pack, looks like this:

package Addition;
use Sub::Exporter;
Sub::Exporter::setup_exporter({ exports => [ qw(plus) ]});

sub plus { my ($x, $y) = @_; return $x + $y; }

this means that when someone used your Addition module, they could have its plus routine imported straight into their package:

use Addition qw(plus);

my $z = plus(2, 2); # this works, because now plus is in the main package

ngl that syntax to set up the exporter is a little verbose, so for the simple case of just naming some exports, you can write this instead:

use Sub::Exporter -setup => { exports => [ qw(plus) ] };

...which is literally the same as the original example β€” except now the exporter is built and installed at compile time. oh, and you typed less. slay πŸ’…


πŸ¦‹ Using Export Groups

you can specify whole groups of things that should be exportable together. these are called groups. (Exporter calls these tags, fyi.) 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 only needs to write:

use Food qw(:fauna);
use Food qw(-fauna);

either one of the above is acceptable, no cap. 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 β€” that's your anti-infinite-loop safety rail 🧚

there are two special groups: all and default.

  • all 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.
  • default is the set of routines to export when nothing specific is requested. by default, there is no default group.

πŸ’œ 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, because it's thoughtful like that πŸŽ€

if you wanted to import lox from the Food package but you're not feeling the name, you could write:

use Food lox => { -as => 'salmon' };

now you'd get the lox routine, but it would be called salmon in your package. iconic.

you can also rename entire groups by using the prefix option:

use Food -fauna => { -prefix => 'cute_little_' };

now you can call your cute_little_rabbit routine. (you can also call 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. and 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 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 -suffix argument πŸ’«

finally β€” and this is the little plot twist β€” if the -as argument to an exported routine is a reference to a scalar, a reference to the routine will be placed in that scalar. iykyk.


⭐ 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. main character energy, honestly πŸ‘‘

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. 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 counter in his package. it will count up by one, and will never interfere with anyone else's counter. every counter is its own little individual, we love boundaries πŸ’–

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. merging, not clobbering, bestie.

notice, too, that in the example above, we gave a reference to a method name rather than a method implementation. by giving the name rather than the subroutine, we make it possible for subclasses of our Package::Counter module to replace the _build_counter method. forward-thinking! 🧠

when a generator is called, it is passed four parameters:

  • the invocant on which the exporter was called
  • the name of the export being generated (not the name it's being installed as)
  • the arguments supplied for the routine
  • the collection of generic arguments

that fourth item is the last major feature that hasn't been covered. cliffhanger resolved ⬇️


πŸ“ 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 πŸ₯— iconic behavior.

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. so like, validate responsibly πŸ’€


πŸ”₯ 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 β€” found family vibes 🫢

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 -prefix or -suffix arguments.


🌈 PERL VERSION 🌈

this library should run on perls released even a long time ago. it should work on any version of perl released in the last five years.

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. (translation: don't come for the version floor, it's not up for negotiation πŸ™…β€β™€οΈ)


πŸ‘€ SEE ALSO πŸ‘€

  • Sub::Exporter for complete documentation and references to other exporters

πŸ’« AUTHOR πŸ’«

Ricardo Signes <cpan@semiotic.systems> β€” the legend himself ✨


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.


okay that's the whole page bestie, go forth and export responsibly πŸ’…

that was perl v5.42.0, dated 2024-03-08, from Sub::Ex...Tutorial(3) β€” mwah, see you in the next manpage πŸ¦‹πŸ’–

πŸ“¦ where this page comes from