Reputation: 29116
Let's consider this example:
#!/usr/bin/env perl
use strict;
use Data::Dumper;
my $node = node(undef, undef, 'root');
my $root = $node;
$node = node($root, $node, 'tom');
push $root->{children}, $node;
$node = node($root, $node, 'clarence');
push $root->{children}, $node;
Data::Dumper::Purity;
#$root->{children}[0]->{younger} = $root->{children}[1];
print Dumper $root;
sub node {
return {
parent => shift,
prev => shift,
name => shift,
children => [],
};
}
Which gives this output:
$VAR1 = {
'parent' => undef,
'prev' => undef,
'name' => 'root',
'children' => [
{
'parent' => $VAR1,
'prev' => $VAR1,
'name' => 'tom',
'children' => []
},
{
'parent' => $VAR1,
'prev' => $VAR1->{'children'}[0],
'name' => 'clarence',
'children' => []
}
]
};
We can clearly see that root
has 2 children named tom
and clarence
. The reference of clarence
on tom
is really clear $VAR1->{'children'}[0]
.
However, if I add a reference on tom
to clarence
with $root->{children}[0]->{younger} = $root->{children}[1];
, the output get messed up:
$VAR1 = {
'parent' => undef,
'prev' => undef,
'name' => 'root',
'children' => [
{
'parent' => $VAR1,
'prev' => $VAR1,
'younger' => {
'parent' => $VAR1,
'prev' => $VAR1->{'children'}[0],
'name' => 'clarence',
'children' => []
},
'name' => 'tom',
'children' => []
},
$VAR1->{'children'}[0]{'younger'}
]
};
Is there any possibility to constraint Data::Dumper
or any other dumper to always consider some keys as references in order to properly display a tree?
Upvotes: 1
Views: 70
Reputation: 126742
There isn't a lot you can do because Data::Dumper
scans structures depth-first, but I suggest that you use
$Data::Dumper::Deepcopy = 1
which will duplicate hash values in the output instead of inserting cross-references. This is the result
$VAR1 = {
'prev' => undef,
'children' => [
{
'parent' => $VAR1,
'name' => 'tom',
'younger' => {
'children' => [],
'prev' => $VAR1->{'children'}[0],
'name' => 'clarence',
'parent' => $VAR1
},
'prev' => $VAR1,
'children' => []
},
{
'children' => [],
'prev' => {
'parent' => $VAR1,
'name' => 'tom',
'younger' => $VAR1->{'children'}[1],
'prev' => $VAR1,
'children' => []
},
'name' => 'clarence',
'parent' => $VAR1
}
],
'parent' => undef,
'name' => 'root'
};
Upvotes: 1