As the others have said, it's because those array elements are referencing the same data structure. A simplified version demonstrating this:
use Data::Dumper;
my $aref = ['x','y'];
my @a = ($aref, $aref);
print Dumper(\@a);
__END__
$VAR1 = [
[
'x',
'y'
],
$VAR1->[0]
];
I hope it's clear that both elements of @a are referring to the same anonymous array, and that's what Data::Dumper is trying to say with $VAR1->[0]: "this element of the array is the same as the first element of the array reference $VAR1".
Note: Unfortunately, the above syntax, when evaled, does not produce the same data structure, because a data structure can't actually reference itself this way - remember that Data::Dumper is a debugging tool. But if you need it, you can get Data::Dumper to output something that can be evaled if you use its Purity option:
use Data::Dumper;
my $aref = ['x','y'];
my @a = ($aref, $aref);
$Data::Dumper::Purity=1;
print Dumper(\@a);
__END__
$VAR1 = [
[
'x',
'y'
],
[]
];
$VAR1->[1] = $VAR1->[0];
This kind of data structure could maybe become an issue if you modify elements in the nested data: In the above example, if I modify $a[0][0], then $a[1][0] will change too, since it's the same anonymous array. But if the rest of the code in your program is only reading this data structure, not modifying it, you won't notice the difference in this regard (Update: code that cares about whether two references are pointing to the same data structure might, like we're seeing here with Dumper).
If you do need all elements of the nested data structure to be different, one way to do that is to use something like Storable's dclone to make a deep copy of the data structures. (There are other ways of course, especially if you know the structure of your input data, but this one has the advantage of being able to copy almost any nested data structure.)
use Data::Dumper;
use Storable qw/dclone/;
my @a = (1,2,3,4,6);
$Data::Dumper::Indent=0;
print Dumper(increment(increment(\@a))), "\n";
sub increment{
my $d = shift;
my @b;
for my $i (1..$#$d){
my @a = @$d[$i-1..$i];
push @b, dclone \@a;
}
return \@b;
}
__END__
$VAR1 = [[[1,2],[2,3]],[[2,3],[3,4]],[[3,4],[4,6]]];
BTW, I think Data::Dump represents these data structures a bit more nicely (and, in a way that can be evaled back into Perl better, if need be):
use Data::Dump;
my $aref = ['x','y'];
my @a = ($aref, $aref);
dd \@a;
__END__
do {
my $a = [["x", "y"], 'fix'];
$a->[1] = $a->[0];
$a;
}
Also, if you want Data::Dumper to display these kinds of data structures as if there were no such references, you can use its Deepcopy option:
use Data::Dumper;
$Data::Dumper::Deepcopy = 1;
$Data::Dumper::Indent = 0;
my $aref = ['x','y'];
my @a = ($aref, $aref);
print Dumper(\@a), "\n";
__END__
$VAR1 = [['x','y'],['x','y']];
But remember this affects the output only, the references haven't changed. This may lead to confusion if you change one element, and another element appears to "magically" change. |