<snip>
> On Tue, Aug 23, 2011 at 10:23 AM, <anand.jaw...@emc.com> wrote:
> I am working on the below code to traverse through a hash, but it throws an
> error which states "Can't coerce array into hash at temp.pl line 6."
>
> Code:
> ===============================================================
> sub hash_walk {
>        my $self = shift;
>     my ($hash, $key_list, $callback) = @_;
>     while (my ($k, $v) = each (%$hash)) {
>        push @$key_list, $k;
>          if (ref($v) eq 'HASH') {
>        $self->hash_walk($v, $key_list, $callback);
>         }
>         else {
>                $callback->($k, \$v, $key_list);
>         }          pop @$key_list;
>                $hash->{$k} = $v;
>     }
>     }
<snip>
>     hash_walk(\%data, [], \&replace_all_val_strings);
>  sub replace_all_val_strings {
>  my ($k, $v, $key_list) = @_;
>     printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $$v, "@$key_list";
>     $$v =~ s/oldstr/newstr/;
>     printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $$v, "@$key_list";
>  }

I couldn't see any point in '@key_list' and am less comfortable with OO 
than I would like to be but unless I missed something I think this does
what you're asking after you add '$self' back in.

    my %foods = (   fruit => { qw / apple 1 banana 2 pear 3 / },
                    nuts  => { pecan => 10, walnut => 20 },
                );

    sub hash_walk
    {   my ($hash, $callback) = @_;
        while (my ($k, $v) = each (%$hash))
        {   if (ref($v) eq 'HASH')
            {   hash_walk($v, $callback);
            }
            else
            {   $callback->($k, \$v);
            }
            $hash->{$k} = $v;
        }
    }

    sub replace_all_val_strings
    {   my ($k, $v) = @_;
        my $new = ++$$v;
        $$v =~ s/$$v/$new/;
    }

    use Data::Dumper;
    print Dumper \%foods;
    hash_walk(\%foods, \&replace_all_val_strings);
    print Dumper \%foods;

HTH,
Mike
-- 
Satisfied user of Linux since 1997.
O< ascii ribbon campaign - stop html mail - www.asciiribbon.org

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to