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}; } }
In reply to recursive hash layer removal question by wertert
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |