A "reference" means a reference to a space in (perl interpreter) memory. It's like the number of a pigeon-hole/post-office box: the number(=address) remains the same but the contents may change any time. And that change will be reflected on all those places in your script where you read that reference. For example:
my @arr = (1,2,3); my $ref = \@arr; # or just [1,2,3] print $ref->[0]; # 1 $arr[0] = 42; print $ref->[0]; # 42
No matter which part of your script you pass that reference, when you do $arr[0] = 42; all these places will automatically see the new value 42. Because you gave them a pigeon-hole (PH) number. They look for the contents of that PH. And when you change the contents, they will see that change.
In the loop foreach my $other you keep changing the contents of just one PH you asked for, outside the loop. Its address remains the same, set in my $piece; So, as anonymonk says, create a new reference each time you loop. The PH will be preserved in memory and in your hash even when my $piece goes out of scope. Because you passed that PH number to your hash, it remains alive (here you may want to read Perl and Garbage Collection).
This is a very powerful feature. You create a data structure in memory, like you do. Then get a reference (its PH number) and then pass that to any part of your (single-threaded) program, e.g. subs, which need to read or write onto that data structure. All changes will be communicated immediately to all clients.
Here is some fun:
use strict; use warnings; use Data::Dumper; my $joe; $joe->{name} = 'joe'; $joe->{age} = 42; my $mary; $mary->{name} = 'mary'; $mary->{age} = 43; my $peter; $peter->{name} = 'peter'; $peter->{age} = 100; my @children = ($joe, $mary); my @family = ($mary, $peter, $joe); my @males = ($joe, $peter); ## oops, Joe is actually written as John $joe->{name} = 'john'; print Dumper(@children); print Dumper(@family); print Dumper(@males);
bw, bliako
In reply to Re: Unwanted cloning of array elements
by bliako
in thread Unwanted cloning of array elements
by oakbox
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |