gfairweather has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to use a hash of hashes in a package but can't quite figure out how to print all the hashes with an accessor.
I create the hash something like this:

sub init_hash { my ($self) = @_; $self->{a_hash}{item1} = {name => 'a', value => '1'}; $self->{a_hash}{item2} = {name => 'b', value => '2'}; $self->{a_hash}{item3} = {name => 'c', value => '3'}; $self->{a_hash}{item4} = {name => 'd', value => '4'}; 1; }

So far so good, and now I can create an accessor to print one of the items from that hash like this:
sub print_item3 { my ($self) = @_; print $self->{a_hash}{item3}{name} . " : " . $self->{a_hash}{item3}{ +value} . "\n"; }

This works and it prints the item, next I want to print the complete hash and so I try something like this:
sub print_all_hash { my ($self) = @_; foreach my $item (keys $self->{a_hash}) { print $self->{a_hash}{$item}{name} . " : " . $self->{a_hash}{$item +}{value} . "\n"; } }

But this doesn't work and throws an error:
Type of arg 1 to keys must be hash (not hash element)

I have tried a number of variations but just can't get the syntax correct and so I am seeking a little help from you guys to put me on track.
Many thanks.

Replies are listed 'Best First'.
Re: Package hash accessor
by CSJewell (Beadle) on Mar 31, 2009 at 22:48 UTC

    A "hash of hashes" is really a hash of hashrefs. No dereferencing required. Therefore, the keys parameter should be:

    (keys %{$self->{a_hash}})

      Fantastic, that solves it. Many many thanks. I don't know how I missed that :)

Re: Package hash accessor
by targetsmart (Curate) on Apr 01, 2009 at 08:20 UTC
    see this Re: autoload usage

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
      Your suggestion addresses the traditional auto-generation of accessors - it doesn't address the problem encountered by the OP - unlike the reply from CSJewell, which does.

      A user level that continues to overstate my experience :-))