satzbu has asked for the wisdom of the Perl Monks concerning the following question:
Hi monks please help me to update this code this is used to replace a hash key with another hash value when i change grouping the input hash keys means it cant work please help me to debug this code
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my %xhash = ('a' => { 'b' => { 'e' => 'E', 'c' => 'C', 'content' => 'B ' }, 'content' => 'A ', 'd' => 'D' }); my %c_hash=('a' => { 'addval' => { 'b' => { 'addval' => { 'e' => { 'addv +al' => {}, 'repv +al' => '5' }, 'c' => { 'addv +al' => {}, 'repv +al' => '3' } }, 'repval' => '2' }, 'd' => { 'addval' => {}, 'repval' => '4' } }, 'repval' => '1' }); sub traverse { my ($hash, $callback, $mode) = @_; return unless ref($hash) eq "HASH"; for my $key (keys %$hash) { my $val = $hash->{$key}; if (ref($val) eq "HASH") { traverse($val, $callback, $mode); if ($mode eq "collect") { if (exists $val->{repval}) { $callback->($key, $val->{repval}); } } } if ($mode eq "replace") { $callback->($key, $val, $hash); } } } my %repl; # lookup table: a => 1, etc. traverse(\%c_hash, sub { my ($key, $val) = @_; $repl{$key} = $val; }, "collect" ); # print Dumper \%repl; # debug traverse(\%xhash, sub { my ($key, $val, $href) = @_; if (exists $repl{$key}) { my $newkey = $repl{$key}; $href->{$newkey} = $val; delete $href->{$key}; } }, "replace" ); print Dumper \%xhash; __END__ $VAR1 = { '1' => { '4' => 'D', 'content' => 'A ', '2' => { '3' => 'C', 'content' => 'B ', '5' => 'E' } } }; _WANT TO CHANGE THE INPUT AS_ my %xhash = ('a' => [{ 'b' => [{ 'e' => ['E'], 'c' => ['C'], 'content' => ['B'] }], 'content' =>['A'], 'd' => ['D'] }]); _OUTPUT FOR THIS INPUT_ my %xhash = (['a' => [{ 'b' => [{ 'e' => ['E'], 'c' => ['C'], 'content' => ['B'] }], 'content' => ['A'], 'd' => ['D'] }]); _REQUIRED OUTPUT_ $VAR1 = { '1' => [{ '4' => ['D'], 'content' => ['A'], '2' => [{ '3' => ['C'], 'content' => ['B'], '5' => ['E'] }] }] };
please help me its very urgent
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: update required for subroutine
by almut (Canon) on Apr 21, 2010 at 09:36 UTC | |
by satzbu (Acolyte) on Apr 21, 2010 at 12:46 UTC | |
by almut (Canon) on Apr 21, 2010 at 12:56 UTC | |
| |
|
Re: update required for subroutine
by GrandFather (Saint) on Apr 21, 2010 at 08:21 UTC | |
|
Re: update required for subroutine
by arc_of_descent (Hermit) on Apr 21, 2010 at 06:47 UTC | |
|
Re: update required for subroutine
by Anonymous Monk on Apr 21, 2010 at 06:39 UTC | |
by Anonymous Monk on Apr 21, 2010 at 08:34 UTC | |
|
Re: update required for subroutine
by pemungkah (Priest) on Apr 21, 2010 at 20:02 UTC |