[tpm] Weird arrary reference bahaviour
Cees Hek
ceeshek at gmail.com
Wed Oct 31 18:20:00 PDT 2007
On 11/1/07, Indy Singh <indy at indigostar.com> wrote:
> Hi Guys,
> Can anyone explain, why taking a reference to an array gives a different
> value on each iteration of this loop. This is the line of code:
> my $r = \@f;
>
> If I move the "my @a" declaration outside the loop I get the same value
> each time.
>
> It seems that on each iteration of the loop a new @f array is created.
> Does that make sense?
>
> Indy Singh
> IndigoSTAR Software -- www.indigostar.com
>
>
> my @foo = ("ford:ltd", "chevy:nova");
> my $x;
> my @a;
>
> foreach $x (@foo) {
> my @f;
> @f = split(/:/, $x);
> my $r = \@f;
> print "r = $r\n";
> push @a, $r;
> }
At the end of each iteration of the loop, @f falls out of scope. But
since you store away a reference to \@f, the data that @f refers to
does not get garbage collected (ie it's refcount has not hit zero).
So during the next iteration of the loop, the memory location that @f
used during the previous iteration is not available to be re-used, so
a new location is assigned to @f.
if you didn't store that reference to @f, then the data would be
garbage collected (ie @f goes out of scope at the end of the
iteration, the refcount is zero and the memory is reclaimed), and Perl
would re-use the same memory location for @f for each iteration.
Cheers,
Cees
More information about the toronto-pm
mailing list