[tpm] Weird arrary reference bahaviour

Indy Singh indy at indigostar.com
Wed Oct 31 18:42:32 PDT 2007


From: "Cees Hek" <ceeshek at gmail.com>
To: "Indy Singh" <indy at indigostar.com>
Cc: <tpm at to.pm.org>
Sent: Wednesday, October 31, 2007 9:20 PM
Subject: Re: [tpm] Weird arrary reference bahaviour


> 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

> At the end of each iteration of the loop, @f falls out of scope.
I would have thought that @f falls out of scope _after_ the closing 
brace, not while still inside it.  But you seem to be right.




More information about the toronto-pm mailing list