in reply to Storing arrays as object variables

Perl uses a reference-counting garbage collection scheme. Declaring the lexical increments the reference counter to one, and storing a reference in the object increments the counter to two. When the @array name goes out of scope, the counter is decremented back to one. Since the object still holds a reference, the actual array data structure will not be garbage collected.

Replies are listed 'Best First'.
Re: Re: Storing arrays as object variables
by flounder99 (Friar) on Jul 20, 2002 at 16:59 UTC
    I always like to give a code example. This is a simple demonstration of how data sticks arround even though the original @array is out of scope. You rarely have to worry about losing data when it goes out of scope. You really have to watch for memory leaks when you create circular references. Read perlreftut and perlref for more info.
    use strict; my $arrayref; { #create a closure for @array my @array = qw(zero one two three); $arrayref = \@array; } # @array is out of scope but @array's data still there print $arrayref->[1],"\n"; # prints "one" $arrayref->[4] = $arrayref; # circular reference. $arrayref = 1; # memory leak ! # @array's memory is never freed # until program ends!

    --

    flounder