为什么选择在单独的语句中声明和初始化词法变量?

pla*_*etp 15 variables perl

这是摘录自 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
        }
    },
);
Run Code Online (Sandbox Code Playgroud)

它为什么用

my $read_watcher; $read_watcher = AnyEvent->io (...
Run Code Online (Sandbox Code Playgroud)

代替

my $read_watcher = AnyEvent->io (...
Run Code Online (Sandbox Code Playgroud)

yst*_*sth 24

由于封闭引用$read_watcher和范围,在其$read_watcher解析为词汇只开始的声明之后,包含的my.

这是故意的,所以像这样的代码引用两个单独的变量:

my $foo = 5;

{
    my $foo = $foo;
    $foo++;
    print "$foo\n";
}

print "$foo\n";
Run Code Online (Sandbox Code Playgroud)