Naming anonymous subroutines

In the “Dynamic Subroutines” chapter, I considered adding the undocumented __ANON__ trick to give anonymous subroutines names. ysth described this in Permonks in 2003 in Named anonymous subs and later showed up in Perl Hacks #57. Although it’s undocumented, several modules use the trick.

I can use carp in an anonymous subroutine:

package ThisPackage;
use Carp qw(cluck);

my $sub = sub {
	cluck "This is a warning";
	return 1;
	};

package OtherPackage;	
$sub->();

Perl doesn’t know what to label the subroutine in the warning message, so it uses ::__ANON__:

This is a warning at sub.pl line 7.
	ThisPackage::__ANON__() called at sub.pl line 12

This can get quite tricky if I’m making many anonymous subroutines—perhaps through some generator function—and I want to know which one is causing the problem.

Inside an anonymous subroutine, I can set the __ANON__ variable to the value that I want to see in the message:

#!/usr/local/perls/perl5.18.1/bin/perl

package ThisPackage;
use Carp qw(cluck);

my $sub = sub {
	local *__ANON__ = "Here I am";
	cluck "This is a warning";
	return 1;
	};

package OtherPackage;	
$sub->();

Even though I don’t use a valid variable name, the warning uses that name:

This is a warning at sub.pl line 8.
	ThisPackage::Here I am() called at sub.pl line 13

I showed a different, more complicated way to do this in The Effective Perler as Enchant closures for better debugging output