in reply to Confused by reference sample code

The key is the my in the sample code. That creates a new variable every time through the loop. Your test uses a global variable instead.

Replies are listed 'Best First'.
Re^2: Confused by reference sample code
by Melly (Chaplain) on Mar 28, 2006 at 22:04 UTC

    Many thanks - I must admit that the difference between 'my' inside a loop and outside in this context had elluded me (the distinction between 'new variable' and 'same variable' is somewhat blurred in this context).

    Question: if the memory allocated to the hash had not been passed by ref. to the array, would perl have released it's memory?

    Tom Melly, tom@tomandlu.co.uk
      if the memory allocated to the hash had not been passed by ref. to the array, would perl have released it's memory?

      Yes. Perl uses reference counting to determine if a variable is still in use. As soon as there are no references to a variable, the memory is released back to Perl (but not necessarilly to the operating system). For example,

      { # Creates a scalar with value 'val1'. my $var1 = 'val1'; # 1 reference to val1. } # $var1 goes out of scope. # 0 references to val1. # No more references to 'val1', so it is released. my $var2; { # Creates a scalar with value 'val1'. my $var3 = 'val2'; # 1 reference to val2. $var2 = \$var3; # 2 references to val2. } # $var3 goes out of scope. # 1 reference to val2. $var2 = 'val3' # 0 references to val2. 1 reference to val3. # No more references to 'val2', so it is released.