# 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
}
},
);
为什么使用
my $read_watcher; $read_watcher = AnyEvent->io (...
而不是
my $read_watcher = AnyEvent->io (...
答案 0 :(得分:24)
因为闭包引用$read_watcher
并且$read_watcher
解析为词法的范围仅以包含my
之后的语句开头。
这是故意的,所以这样的代码引用了两个独立的变量:
my $foo = 5;
{
my $foo = $foo;
$foo++;
print "$foo\n";
}
print "$foo\n";