Perl: array reference versus anonymous array

This might be a dumb question ... The following code displays the contents of @arrayref and @arraycont respectively. Pay attention to the difference between them and the way they are assigned values. I know what an anonymous array does, but can anyone explain why there is a difference?

Many thanks.

 @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"; 

exits

 5 6 7 8 5 6 7 8 1 2 3 4 5 6 7 8 
+8
arrays perl
source share
2 answers

This creates a shallow copy of the array:

$arraycont[0] = [@array];

While this just creates a link to it:

$arrayref[0] = \@array;

Since you later modify the array:

@array = qw(5 6 7 8);

arrayref still points to the same location of the array in memory, and so when dereferenced in print statements, it prints the current values โ€‹โ€‹of the array 5 6 7 8 .

+11
source share

The first block stores the address @array . The references are similar to the "live broadcast" , you get the current status. Therefore, if you create a link to @array, for example \ @array, when you de-link to it, you always get what @array indicates when the link was canceled, When you delete @array , (5 6 7 8)

When you do [@array] , how to record the live stream to your disk. Therefore, when you (re) play the recorded content, you get what was streamed during recording. So when you refer to $ arraycont [0] , you get what @array had while copying, that is (1 2 3 4)

+3
source share

All Articles