How do I get a reference to a function from within the function? [duplicate]
Possible Duplicate:
In Perl, how can a subroutine get a coderef that points to itself?
Is there a way to get a reference to a function from within that function without using the name?
I've recently found myself repeatedly writing code that smells of an anti-pattern. Data::Dump supports filters but (as of version 1.16) they aren't applied recursively. To work around that I've been writing things like this:
sub filter {
my ($context, $node) = @_;
# ...
return { dump => dumpf($something, \&filter) };
}
This works, but the \&filter
reference is starting to bug me. It creates maintenance overhead if the function is renamed or copied elsewhere as a template for a new filter. I'd like to replace it with something like __SUB__
(if Perl had such a thing).
For named subroutines you can use caller
to get the name and then take a reference to it:
sub foo {
state $self = \&{(caller(0))[3]};
#...
# call $self->();
}
This doesn't work for anonymous subroutines, which get "names" like main::__ANON__
.
精彩评论