Unlike e.g. array refs, every code ref has a backreference to its glob (so that when you call it,
caller can know the sub name). This is fairly easily accessible with the B module (which provides introspection facilities for perl thingies):
use B;
sub coderef2name {
eval {
my $obj = B::svref_2object( shift() );
$obj->GV->STASH->NAME . "::" . $obj->GV->NAME;
} || undef;
}
Returns something like pkgname::__ANON__ for anonymous subs, or undef if something goes wrong (like being passed an array ref instead of a code ref).
Updated to use GV->STASH->NAME, not STASH->NAME. Thanks, betterworld