Thanks a lot for the suggestions and solution. Regards, Anand
-----Original Message----- From: Shlomi Fish [mailto:shlo...@shlomifish.org] Sent: Tuesday, August 23, 2011 5:09 PM To: Jawaji, Anand Cc: beginners@perl.org Subject: Re: Hash of Hashes - Error Hi Anand, On Tue, 23 Aug 2011 05:57:02 -0400 <anand.jaw...@emc.com> wrote: > Hi All, > > 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." > First of all, let me note that the indentation on that code is inconsistent and erratic. But I was able to fix it by importing it into Vim and using the "=" key (= "format") and some manual tweaks. Here is the correct version: [CODE] #!/usr/bin/perl use strict; use warnings; 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; } } my %data = ( a => { ab => 1, ac => 2, ad => { ada => 3, adb => 4, adc => { adca => 5, adcb => 6, }, }, }, b => 7, c => { ca => 8, cb => { cba => 9, cbb => 10, }, }, ); 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"; } [/CODE] Now after I did that, I used the perl debugger ("perl -d") to debug the code (see http://perl-begin.org/topics/debugging/ ), and realised that the problem was that hash_walk expects 4 arguments (including "$self" which is the object handle), while it is only given 3 in the initial call, which fails. Do you need the "$self" or is there a good reason for that? If you do, read the Object Oriented programming resources at http://perl-begin.org/topics/object-oriented/ , because otherwise it's just cargo-cult programming. Also see: http://perl-begin.org/tutorials/bad-elements/ Regards, Shlomi Fish -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ First stop for Perl beginners - http://perl-begin.org/ Trying to block Internet pornography is like climbing a waterfall and trying to stay dry. (— one of Shlomi Fish’s Internet Friends) Please reply to list if it's a mailing list post - http://shlom.in/reply .