开发者

How do I get a reference to a function from within the function? [duplicate]

This question already has answers here: 开发者_Python百科 Closed 12 years ago.

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__.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜