wertert has asked for the wisdom of the Perl Monks concerning the following question:
I have a data structures made up of HOHOH etc which represents a tree. I am trying to find a way of removing an entire 'layer' of the tree while keeping the other layers intact and still linked to each other. As an example I may start with
and I want to remove all of 'level' 2 ( ie L,C,Q,T ) leaving me with;$W={ 'A' => { 'L' => { 'D'=>99, 'X'=>99, }, 'C' =>{ 'E'=>99 }, }, 'X' => { 'Q'=>{ 'O'=>99, }, 'T'=>{ 'U'=>99, }, }, };
Doesn't sound too bad ? The only complication is the tree can have any number of layers so I've been leaning towards various recursive ideas and using dclone but I'm not getting anywhere fast. I'm also thinking that it's probably easier to create a new hash instead of changing the source, unlike my lame effort below.$X={ 'A' => { 'D'=>99, 'X'=>99, 'E'=>99 }, 'X' => { 'O'=>99, 'U'=>99, }, };
output is;printTree($W); # just dumps HOHOH - could use data::dumper - remove +d remove1($W,2); # ie remove layer 2 ( counting from 1 ) print "--------------------\n"; printTree($W); sub remove1 { my($refToHash)=shift; my($stage)=shift; foreach $a (keys %{$refToHash}) { if($depth==$stage-1) # then we've hit the level before the lev +el to be removed/ { print "removing $a\n"; foreach $b (keys %{$refToHash->{$a}}) { $refToHash->{$b} = $refToHash->{$a}->{$b}; delete($refToHash->{$a}); } } else { $depth++; remove1($refToHash->{$a},$stage); $depth--; } } }
so sort of ok but I'm really not happy with it. Removing layer 1 is also ok but layer 3 does not work. Can anyone suggest a better way of doing this. I've been staring at this (from Randal L. Schwartz, Perl hacker) for the last 3 hours and trying to think of a way of making it layer sensitive ...perl delete_mid2.pl A C E L D X X Q O T U removing C removing L removing Q removing T -------------------- A D E X X O U
I would really appreciate ANY suggestions. Thanks in advance. Jeffsub deep_copy { my $this = shift; if (not ref $this) { return $this; } elsif(ref $this eq "HASH") { return {map { $_ => deep_copy($this->{$_}) } keys %$this}; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: recursive hash layer removal question
by Roy Johnson (Monsignor) on May 10, 2005 at 17:55 UTC | |
|
Re: recursive hash layer removal question
by Animator (Hermit) on May 10, 2005 at 17:27 UTC | |
by wertert (Sexton) on May 10, 2005 at 17:38 UTC | |
|
Re: recursive hash layer removal question
by Forsaken (Friar) on May 10, 2005 at 21:27 UTC | |
by wertert (Sexton) on May 11, 2005 at 15:01 UTC | |
by wertert (Sexton) on May 11, 2005 at 17:12 UTC | |
|
Re: recursive hash layer removal question
by TedPride (Priest) on May 10, 2005 at 19:42 UTC | |
by wertert (Sexton) on May 11, 2005 at 14:01 UTC | |
by Transient (Hermit) on May 11, 2005 at 14:24 UTC |