in reply to Beautiful recursive print
watch out for cyclic structures.
I think Dumper does it with a 'global' hash of all places already visited.use strict; use warnings; use Data::Dumper; no warnings 'once' ; local $Data::Dumper::Sortkeys=1; local $Data::Dumper::Indent=1; use warnings; my $c={}; $c->{'1top'}={name=>'1top',childs=>[],parent=>undef}; makechild(name=>'child1',parent=>'1top'); makechild(name=>'child2',parent=>'1top'); makechild(name=>'child21',parent=>'child2'); makechild(name=>'child22',parent=>'child2'); print Dumper($c); sub makechild{ my %args=@_; my $node={}; $c->{$args{name}}=$node; $node->{name}=$args{name}; $node->{childs}=[]; my $parent=$c->{$args{parent}}; $node->{parent}=$parent; push @{$parent->{childs}},$node; }
$VAR1 = { '1top' => { 'childs' => [ { 'childs' => [], 'name' => 'child1', 'parent' => $VAR1->{'1top'} }, { 'childs' => [ { 'childs' => [], 'name' => 'child21', 'parent' => $VAR1->{'1top'}{'childs'}[1] }, { 'childs' => [], 'name' => 'child22', 'parent' => $VAR1->{'1top'}{'childs'}[1] } ], 'name' => 'child2', 'parent' => $VAR1->{'1top'} } ], 'name' => '1top', 'parent' => undef }, 'child1' => $VAR1->{'1top'}{'childs'}[0], 'child2' => $VAR1->{'1top'}{'childs'}[1], 'child21' => $VAR1->{'1top'}{'childs'}[1]{'childs'}[0], 'child22' => $VAR1->{'1top'}{'childs'}[1]{'childs'}[1] };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Beautiful recursive print
by BillKSmith (Monsignor) on Mar 17, 2017 at 14:17 UTC | |
by choroba (Cardinal) on Mar 20, 2017 at 09:04 UTC |