in reply to Hash handling error

( for reference: for loop error )

As every value in your %xhash structure is now wrapped in an array (including its hashes), you'd need to adapt the traverse() routine to dive into those arrays. For example:

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); } } }

Output:

$VAR1 = { '1' => [ { '4' => [ 'D' ], 'content' => [ 'A' ], '2' => [ { '3' => [ 'C' ], 'content' => [ 'B' ], '5' => [ 'E', 'V' ] } ] } ] };

(Also, as "$hash" has now become a misnomer, I'd change it to something more generic, like $node, or some such... but I left that for you to do :)