Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: array reference versus anonymous array

Tags:

arrays

perl

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   
like image 744
wen.huang Avatar asked May 01 '12 04:05

wen.huang


1 Answers

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.

like image 138
yamen Avatar answered Oct 18 '22 05:10

yamen