This is an excerpt from AnyEvent::Intro
# register a read watcher
my $read_watcher; $read_watcher = AnyEvent->io (
fh => $fh,
poll => "r",
cb => sub {
my $len = sysread $fh, $response, 1024, length $response;
if ($len <= 0) {
# we are done, or an error occurred, lets ignore the latter
undef $read_watcher; # no longer interested
$cv->send ($response); # send results
}
},
);
Why does it use
my $read_watcher; $read_watcher = AnyEvent->io (...
instead of
my $read_watcher = AnyEvent->io (...
?
Because the closure references
$read_watcherand the scope at which$read_watcherresolves to the lexical only begins with the statement after that containing themy.This is intentional so that code like this refers to two separate variables: