[tpm] Weird arrary reference bahaviour

Uri Guttman uri at stemsystems.com
Wed Oct 31 20:39:46 PDT 2007

>>>>> "IS" == Indy Singh <indy at indigostar.com> writes:

  IS> Ok, thanks, I believe you. I just didn't expect that.  I was
  IS> thinking in C++ terms, where that variable would be declared on
  IS> the stack frame and would persist until the loop exits.

it is due to perl's reference counting. all lexicals are allocated from
the heap (not the stack) and so they can have references to them that
keeps them alive. my does both a compile time and run time stuff. the
run time stuff includes allocating the variable storage. if my is
executed again and there is are live references to that variable, it
will allocate a new one. this is one way to create a new anon ref. these
do the exact same thing:

	$k = [ 1, 3 ] ;
	$k = do{ my @k = (1, 3) ; \@k } ;

and each time you execute those lines, a new anon array ref is
created. your sub (or rather loop) does the same thing. saving a ref to
the lexical array in that scope means the array will not be freed up
after the loop iterates by hitting its end. so a new array and
subsequently a new ref address are created the next time. by declaring
the array before the loop, it never executes the my runtime part in the
loop and so the ref stays the same as the array stays the same.


Uri Guttman  ------  uri at stemsystems.com  -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------  http://jobs.perl.org

More information about the toronto-pm mailing list