Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: 'my' Variable life cycle

by gamache (Friar)
on Mar 07, 2008 at 15:24 UTC ( [id://672797] : note . print w/replies, xml ) Need Help??

in reply to 'my' Variable life cycle

As long as at least one reference to a variable exists, the variable will not be garbage-collected. So in this example:
sub foo { my @x = qw(a b c); return \@x } my $f = foo();
...@x's contents remain, and $f now holds a reference to @x, such that $f->[0] eq 'a'. But here:
sub foo { my @x = qw(a b c); return \@x } foo();
...@x can be garbage-collected as normal, since the reference to @x gets dropped on the floor.

Replies are listed 'Best First'.
Re^2: 'my' Variable life cycle
by ikegami (Patriarch) on Mar 09, 2008 at 04:21 UTC

    The following shows the memory being re-used.

    sub func1 { my $x; print(\$x, "\n"); return \$x } sub func2 { my $x; print(\$x, "\n"); return } push @a, func1() for 1..5; print("\n"); func1() for 1..5; print("\n"); func2() for 1..5; print("\n");
    SCALAR(0x226d1c) SCALAR(0x225ffc) SCALAR(0x226cb0) SCALAR(0x1830a6c) SCALAR(0x1830a84) SCALAR(0x1830a9c) SCALAR(0x1830ab4) SCALAR(0x1830a9c) SCALAR(0x1830ab4) SCALAR(0x1830a9c) SCALAR(0x1830910) SCALAR(0x1830910) SCALAR(0x1830910) SCALAR(0x1830910) SCALAR(0x1830910)

    Note that the implementation of lexicals actually differs a lot from your description, but your post is an accurate description of how lexicals should be perceived to work.

Re^2: 'my' Variable life cycle
by Anonymous Monk on Mar 07, 2008 at 15:30 UTC
    So that I need to clean the large list and hash by myslef before I exit the function in order to release the memory?

      If you don't return that variable somehow from the function, Perl will reclaim the memory when the function returns. If you do return that variable somehow from the function, you probably don't want to release its memory.

      No, if you want a variable's memory to be released when the function exits, you need to not return a reference to that variable.