Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

variables

perl

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

?

like image 816
planetp Avatar asked Jul 17 '11 20:07

planetp


1 Answers

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";
like image 163
ysth Avatar answered Oct 01 '22 08:10

ysth