这是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
}
},
);
为什么使用
my $read_watcher; $read_watcher = AnyEvent->io (...
代替
my $read_watcher = AnyEvent->io (...
?
最佳答案
因为闭包引用$read_watcher
,并且$read_watcher
解析为词法的范围仅从包含my
的语句之后的语句开始。
这是有意的,因此这样的代码引用了两个单独的变量:
my $foo = 5;
{
my $foo = $foo;
$foo++;
print "$foo\n";
}
print "$foo\n";
关于perl - 为什么要选择在单独的语句中声明和初始化词汇变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6726504/