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_watcher
and the scope at which $read_watcher
resolves to the lexical only begins with the statement after that containing the my
.
This is intentional so that code like this refers to two separate variables:
my $foo = 5;
{
my $foo = $foo;
$foo++;
print "$foo\n";
}
print "$foo\n";
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