in reply to Re: How to extract a row or column of two-dimensional hash
in thread How to extract a row or column of two-dimensional hash

Toolic, I had already read the link you provided (and I am using #strict in my code), but didn't find what I needed. Let me try to ask again, using the examples provided in the link (with a few values changes). Please understand also that I've consulted about six Perl books (3 Llama ones) in search of the answer, so I've spent a fair bit of time on this.) I want to count the number of members of each family named jane. I tried the following code:
#to make this easier to read, HoH is defined below.
my ($group);
for $group ("simpsons","jetsons" ) {
my $janemembers=grep {$_ eq "jane"} values $HoH{$group};
}
The error given is that "Type of arg1 to values must be hash (not hash element). What's going wrong??
%HoH = (
flintstones => {
lead => "fred",
pal => "barney",
},
jetsons => {
lead => "george",
wife => "jane",
kid => "jane",
},
simpsons => {
lead => "homer",
wife => "marge",
kid => "bart",
},
);
  • Comment on Re^2: How to extract a row or column of two-dimensional hash

Replies are listed 'Best First'.
Re^3: How to extract a row or column of two-dimensional hash
by merlyn (Sage) on Jan 11, 2008 at 21:37 UTC
    The error message "Type of arg1 to values must be hash (not hash element)" is giving you precisely the fix you need.

    $HoH{$group} is a hash element. The keys function you have in front of it wants a hash, not a hash element. Since that hash element is a reference to the actual hash, you must dereference the reference to get to the hash. In this case, wrap %{ ... } around it, as in %{$HoH{$group}}, and put keys in front of that.

    I'm surprised you checked "3 llamas". The llama doesn't talk about references (deliberately, because there's only so much we can cover in a week). You want The Alpaca instead, which covers this topic (and more!).

Re^3: How to extract a row or column of two-dimensional hash
by toolic (Bishop) on Jan 11, 2008 at 21:56 UTC
    When posting code, please use "code" tags, not "br" tags, as described in Writeup Formatting Tips.

    Updated: $HoH{$group} is a reference to a hash. I refactored your code as follows:

    #!/usr/bin/env perl use warnings; use strict; my %HoH = ( flintstones => { lead => "fred", pal => "barney", }, jetsons => { lead => "george", wife => "jane", kid => "jane", }, simpsons => { lead => "homer", wife => "marge", kid => "bart", }, ); my $total_jane_count = 0; for my $group ("simpsons" ,"jetsons" ) { my %family_hash = %{ $HoH{$group} }; for my $name (values %family_hash) { if ($name eq 'jane') { $total_jane_count++ } } } print "total_jane_count = $total_jane_count\n";

    This prints:

    total_jane_count = 2
      Toolic, thank you for the code.