sub_util_set_subname#

Assign a name to a subroutine reference in place.

Synopsis#

use Sub::Util qw(set_subname);
my $code = set_subname 'My::Pkg::name', sub { ... };

What you get back#

The same code reference, now reporting $name under subname, caller, and stack traces. If $name contains :: or a quote-style separator ('), the left part becomes the package and the right part the short name. An unqualified name is attached to the current compilation package.

Examples#

my $sub = set_subname 'My::Thing::handler', sub { process(@_) };
print Sub::Util::subname($sub);        # 'My::Thing::handler'
## Naming closures so stack traces are readable:

for my $op (qw( add sub mul )) {
    $dispatch{$op} = set_subname "op_$op", sub { ... };
}

Edge cases#

  • Croaks with Not a subroutine reference for non-CODE arguments.

  • Croaks with set_subname: not enough arguments on missing args.

Differences from upstream#

Fully compatible with upstream.

See also#

  • subname — read back the fully qualified name.

  • set_prototype — adjust the prototype of a code reference.