In Perl, how can a subroutine get a coderef that points to itself?

后端 未结 5 774
情歌与酒
情歌与酒 2020-12-24 07:02

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

5条回答
  •  渐次进展
    2020-12-24 07:35

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

提交回复
热议问题