The elements of @mass_info are references to annonymous hashes. If you were to just print out the value of $_, you would see something like this:

HASH(0x804e054)

The first snippet of code fails because you are trying to access the 'PID' element of the %_ hash, as this does not exist, then you get nothing output. If you had run perl with warnings on (-w) then you would have seen a warning about the use of an unitialised value where this was used.

The second example works because you are dereferencing the reference held in $mass_info[0] by the use of the {PID}. Another way to write this is as $mass_info[0]->{PID} which is clearer, as it shows that you are accessing the PID element of the hash which is 'pointed' too by $mass_info[0].

Your first loop can be made to work by using this syntax:

foreach (@mass_info) { print $_->{PID}, "\n"; }

If you had a hash with many elements stored in $mass_info[0] then you would need to iterate over the values held in it using a syntax like this:

foreach my $hash_ref (@mass_info) { foreach (keys %{$hash_ref}) { print "$_ => ${$hash_ref}{$_}\n"; } }

For more information, you should refer to the perldsc, perllol, perlreftut and perlref manpages. You have uncovered one of the most powerful features of perl, the way to easily create complicated data structures.


In reply to Re: Foreach on an array (of hashes) by quidity
in thread Foreach on an array (of hashes) by LeGo

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.