Dear monks,
I'd like to have a reference to an array element (or hash element) which is updated as the original array is changed. See code below:
print "--------Trying with arrays-------\n";
my @a = (0, 1, 2, 3);
my $ar = \@a; # Array reference
my $air = \$a[0]; # Reference to member of an array
print "Define array >@a<\nCreate a reference to \$a[0]\n";
print "array ref: >@$ar< \n";
print "array index ref: >$$air<\n";
@a = ('a','b','c');
print "Change array to >@a<\n";
print "array ref: >@$ar< \n";
print "array index ref: >$$air<\n"; # <--- I'd like to get "a" here
print "--------Trying with strings-------\n";
my $s = "string";
my $sr = \$s;
print "orignal: >$s<\n";
print "reference: >$$sr<\n";
$s = "changed string";
print "string: >$s<\n";
print "string reference: >$$sr<\n";
OUPUT:
--------Trying with arrays-------
Define array >0 1 2 3<
Create a reference to $a[0]
array ref: >0 1 2 3<
array index ref: >0<
Change array to >a b c<
array ref: >a b c<
array index ref: >0<
--------Trying with strings-------
orignal: >string<
reference: >string<
string: >changed string<
string reference: >changed string<
It works with the string, but it doesn't work with the array element. I'd like to get the updated array element when dereferencing.
This example is simplified. The original problem is a referenced variable for a Tk Checkbutton where the referent get's updated by another subroutine, but the reference still shows the old value.
I don't want to update the data through the reference as it's a more complex structure which makes it much easier to asign a whole new array instead of looping through it and update each single element.
Help, ideas, .. are greatly appreciated as I couldn't find anything suitable in the net or I'm looking for the wrong phrases. ;