This may be a silly question... The following code outputs the contents of @arrayref
and @arraycont
respectively. Note the difference between them
This creates a shallow copy of the array:
$arraycont[0] = [@array];
Whereas this just creates a reference to it:
$arrayref[0] = \@array;
Since you later modify the array:
@array = qw(5 6 7 8);
arrayref
still points to the same array location in memory, and so when dereferenced in the print statements it prints the current array values 5 6 7 8
.
You made stored references to a single array in both $arrayref[0]
and $arrayref[1]
. You
should have used different arrays.
my @refs;
my @array1 = qw(1 2 3 4);
push @refs, \@array1;
my @array2 = qw(5 6 7 8);
push @refs, \@array2;
In practice, my
is executed in each pass of a loop, creating a new array each time.
my @refs;
while ( my @row = get() ) {
push @refs, \@row;
}
In rare occasions where you have to clone an array, you can use:
use Storable qw( dclone );
push @refs, [ @row ]; # Shallow clone
push @refs, dclone(\@row); # Deep clone
The first block stores the address of @array. REferences are like 'live streaming', you get current status. So if you create a reference to @array, like \@array, when you de-reference it you will always get what @array points at the moment of de-reference. When you de-refer @array was having (5 6 7 8)
When you do [@array] its like recording the live streaming into your disk. So when you (re)play the recorded content you get what was
streamed at the time of recording. So when you refer $arraycont[0] you get what @array was having at the time of copying that is
(1 2 3 4)