princepawn has asked for the wisdom of the Perl Monks concerning the following question:

{ my $ftp = Net::FTP->new('some.host') ; }
what happens when this lexical variable is destroyed? Ie, is DESTROY automatically called? Where would I read in the Perl documentation to know this?

Replies are listed 'Best First'.
Re: what happens when lexical variables go out of scope?
by nardo (Friar) on Jun 14, 2001 at 05:29 UTC
    From perldoc perlobj:
    Destructors When the last reference to an object goes away, the object is automatically destroyed. (This may even be after you exit, if you've stored references in global variables.) If you want to capture control just before the object is freed, you may define a DESTROY method in your class.
Re: what happens when lexical variables go out of scope?
by ariels (Curate) on Jun 14, 2001 at 10:49 UTC
    In your case, $ftp is the only reference to the Net::FTP object. $ftp goes out of scope at the end of the block, so the object gets DESTROYed at that point.

    For code like this:

    { my $connection; { my $ftp = Net::FTP->new('some.host'); $connection->{ftp} = $ftp; } #1 # Do stuff with $connection->{ftp}... } #2
    $ftp goes out of scope at #1, but there's still a reference being held (in $connection->{ftp}!), so the Net::FTP only gets destroyed at #2.

    Think of a "reference" as an arrow pointing to a thingy. It goes from an lvalue (something that's assignable, like a scalar variable or a slot in an array or in a hash) to a thingy. The thingy knows how many arrows point at it; it goes away when the last arrow goes away.