For learning purposes, I am toying around with the idea of building event-driven programs in Perl and noticed that it might be nice if a subroutine that was registered as an event handler could, on failure, just schedule another call to itself for a later time. So far, I have come up with something like this:
my $cb; my $try = 3; $cb = sub { my $rc = do_stuff(); if (!$rc && --$try) { schedule_event($cb, 10); # schedule $cb to be called in 10 seconds } else { do_other_stuff; } }; schedule_event($cb, 0); # schedule initial call to $cb to be performed ASAP
Is there a way that code inside the sub can access the coderef to that sub so I could do without using an extra variable? I'd like to schedule the initial call like this.
schedule_event( sub { ... }, 0);
I first thought of using caller(0)[3]
, but this only gives me a function name, (__ANON__
if there's no name), not a code reference that has a pad attached to it.
__SUB__
has been added in 5.16, providing this usability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With