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
I think Sub::Current will fix your problem.
To get a reference to the current subroutine without using an extra variable, you can use a tool from functional programming, the Y-combinator, which basically abstracts away the process of creating the closure. Here is a perlish version:
use Scalar::Util qw/weaken/;
sub Y (&) {
my ($code, $self, $return) = shift;
$return = $self = sub {$code->($self, @_)};
weaken $self; # prevent a circular reference that will leak memory
$return;
}
schedule_event( Y { my $self = shift; ... }, 0);
__SUB__ has been added in 5.16, providing this usability.
If you don't change $cb
's value again, you can use that. If not, define a scalar to hold that and don't change it ever again. For example:
my $cb = do {
my $sub;
$sub = sub { contents using $sub here }
}
Using a fixed-point combinator, you can write your $cb function as if the first argument was the function itself:
sub U {
my $f = shift;
sub { $f->($f, @_) }
}
my $cb = sub {
my $cb = shift;
...
schedule_event(U($cb), 10);
...
}
schedule_event(U($cb), 0);