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

Hi monks, I found I can do the thing that: I created the vector variable within the function using my, after some processing I return this variable reference to this caller, I found the variable content is same as it inside the function? Is this the reference magic? If I not using reference to return the 'my' variable, will they go to the garbage collection after the function returned?

Replies are listed 'Best First'.
Re: 'my' Variable life cycle
by gamache (Friar) on Mar 07, 2008 at 15:24 UTC
    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.

      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.

      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.
Re: 'my' Variable life cycle
by olus (Curate) on Mar 07, 2008 at 15:23 UTC