Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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

like image 670
Michael Carman Avatar asked Jan 23 '26 03:01

Michael Carman


1 Answers

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

like image 144
Michael Carman Avatar answered Jan 25 '26 23:01

Michael Carman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!