planetp
planetp

Reputation: 16115

Why would one choose to declare and initialize a lexical variable in separate statements?

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 (...

?

Upvotes: 15

Views: 472

Answers (1)

ysth
ysth

Reputation: 98398

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";

Upvotes: 24

Related Questions