This may be a silly question… The following code outputs the contents of @arrayref and @arraycont respectively. Note the difference between them and the way the values of them are assigned. I know what the anonymous array does, but can anybody explain why there is a difference?
Thank you very much.
@arrayref = ();
@array = qw(1 2 3 4);
$arrayref[0] = \@array;
@array = qw(5 6 7 8);
$arrayref[1] = \@array;
print join "\t", @{$arrayref[0]}, "\n";
print join "\t", @{$arrayref[1]}, "\n";
@arraycont = ();
@array = qw(1 2 3 4);
$arraycont[0] = [@array];
@array = qw(5 6 7 8);
$arraycont[1] = [@array];
print join "\t", @{$arraycont[0]}, "\n";
print join "\t", @{$arraycont[1]}, "\n";
outputs
5 6 7 8
5 6 7 8
1 2 3 4
5 6 7 8
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);arrayrefstill points to the same array location in memory, and so when dereferenced in the print statements it prints the current array values5 6 7 8.