sub _capture_weakselfIt's quite a useful little method for creating a new CODE ref around either a given code ref, or a method on the object. This CODE ref captures a reference to the object, passing it as the first argument. This makes it useful for passing around elsewhere, perhaps as an event callback (as it happens, this method lives in IO::Async::Notifier). Because the object ref is stored weakly in this closure, it means the returned closure can safely be stored in the object itself without creating a cycle.
{
my $self = shift;
my ( $code ) = @_; # actually bare method names work too
weaken $self;
return sub { $self->$code( @_ ) };
}
It's sufficiently useful that I feel sure this technique must have a name, but so far I'm failing to find one. I manage to keep reading the name here as "capture weasel". This gives me an idea - perhaps it could be said this closure has been weaseled; short for wea(k)sel(f)ed.
my $weasled_code = $notifier->_capture_weakself( sub {What does anyone think here? Does this technique have a name already? If not; does this seem suitable? I find it unlikely this name already exists somewhere else in CompSci (FOLDOC doesn't have a use in this sense), so it would be a good unique name...
my $self = shift;
my ( $x, $y ) = @_;
....
} );
$weaseled_code->( 123, 456 );
*groan*
ReplyDelete