24 days of Perl code from RJBS! Feed

Bringing out the Good Exporter for Company

Sub::Import - 2010-12-02

The Illusion of Sophistication

Sub::Exporter, covered in the first Advent post last year, describes itself as "a sophisticated exporter for custom-built routines." This is in contrast to Exporter, which is, well... chocked full of near-adequacy.

Sometimes, though, you're stuck working with some code that you don't control and that uses the plain old Exporter. Sub::Import gets around this problem by letting you import from that library with a number of the features otherwise found only in Sub::Exporter.

For example, say you want to use the useful but horribly named natatime routine from List::MoreUtils, and you want to give it a name that won't make you constantly wonder, "What's natural atime?" It's easy to use Sub::Import to get apply Sub::Exporter's renaming facility:


1: 
2: 
3: 

 

use Sub::Import 'List::MoreUtils' => natatime => { -as => 'iterate_by_n' };

my $iterator = iterate_by_n 3, @list;

 

The import-to-scalar rename would work, too:


1: 
2: 
3: 
4: 

 

my $by_n;
use Sub::Import 'List::MoreUtils' => natatime => { -as => \$by_n };

my $iterator = $by_n->(3, @list);

 

You're not limited to renaming single routines, either. You can use the prefix and suffix renaming for groups:


1: 
2: 
3: 
4: 
5: 

 

use Sub::Import 'Perl6::Junction' => -ALL => { -suffix => '_junction' };

if ($input == any_junction(1, 2, 3)) {
  say "$input is okay";
}

 

Many other advanced features are available too, like custom installers or generators, so even if you're working with a library that's still using stock Exporter, you're not stuck with its limitations.

See Also