http://www.perlmonks.org?node_id=835943

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