in reply to Perl/Tk and the "-variable => \$var" option
When I run that (macosx, perl 5.8.1), I find that address of the array ("\@array") remains the same, but the two instances of $array[0] have different memory addresses.use strict; my @array = ( 1, 2, 3, 4 ); print \@array,$/; my $ar0a = \$array[0]; @array = ( 5, 6, 7, 8 ); print \@array,$/; my $ar0b = \$array[0]; print "$ar0a :: $ar0b\n"; # will stringify memory address
Obviously, when you assign a scalar to $array[$index] (given that this array element already has a value), you end up using the original memory address and overwriting the value that is stored there. When you assign a new list to the array, the act of instantiating a list (using the parens) on the rhs of the assignment involves allocating new memory to hold that list, and the lhs array now refers to that new allocation, instead of any previous one.
update: So, the way to make your Perl/Tk script do what you want is to always use a for loop to reset values in the array, so as to preserve the original memory addresses of the elements -- e.g. if you add these lines to the test case above, and print the address of element 0, you'll see that it doesn't change:
my $i = 0; $array[$i++] = $_ for ( 5, 6, 7, 8 );
|
|---|