TL;DR

Getting the name of a sub and other amenities with Sub::Util.

After writing about Sub::Import I also decided to give Sub::Util a try. It actually popped up while I was looking for Sub::Import’s because it does something… in the same area.

Let’s expand the example from the last time:

#!/usr/bin/env perl
use 5.024;
use warnings;
use experimental qw< postderef signatures >;
no warnings qw< experimental::postderef experimental::signatures >;

use FindBin '$Bin';
use lib "$Bin/local/lib/perl5", "$Bin/lib";

use Sub::Import 'MIME::Base64', encode_base64 => {-as => 'e64'},
use Sub::Util qw< subname set_subname >;

say 'e64 is currently ', subname(\&e64);
set_subname('e64, but for messing up!', \&e64);
say 'e64 is now known as "', subname(\&e64), '" in the right circles';

Output:

e64 is currently MIME::Base64::encode_base64
e64 is now known as "main::e64, but for messing up!" in the right circles

Sub::Util contains a few functions, two of which are related to a sub’s name. The first one, subname, tells you what’s the current name of a sub reference:

say 'e64 is currently ', subname(\&e64);

# e64 is currently MIME::Base64::encode_base64

The other one is set_subname, which allows to set the name but only for consumption by subname or other introspection code. In other terms, it does not install a sub with that name, it only record the association between the provided sub reference and a string. Which means that… the name can be whatever string!

This is why this works:

set_subname('e64, but for messing up!', \&e64);
say 'e64 is now known as "', subname(\&e64), '" in the right circles';

# e64 is now known as "main::e64, but for messing up!" in the right circles

I think this is brilliant!