这是从
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 $foo = 5; { my $foo = $foo; $foo++; print "$foo\n"; } print "$foo\n";