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.


In reply to Package hash accessor by gfairweather

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.