Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-24 05:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found