in reply to update required for subroutine
Isn't this pretty much exactly what we've already had in Hash handling error?
The only difference I can spot is that the value associated with 'e' / 5 in that node had been ['E','V'] instead of ['E'].  The solution I suggested should equally be applicable.
Update: complete code (as I understand your task) — just in case:
#!/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) = @_; traverse($hash->[0], $callback, $mode) if ref($hash) eq "ARRAY"; return unless ref($hash) eq "HASH"; for my $key (keys %$hash) { my $val = $hash->{$key}; if (ref($val)) { 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' ] } ] } ] };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: update required for subroutine
by satzbu (Acolyte) on Apr 21, 2010 at 12:46 UTC | |
by almut (Canon) on Apr 21, 2010 at 12:56 UTC | |
| A reply falls below the community's threshold of quality. You may see it by logging in. |