Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Foreach on an array (of hashes)

by quidity (Pilgrim)
on Nov 21, 2000 at 08:10 UTC ( #42648=note: print w/ replies, xml ) Need Help??

in reply to Foreach on an array (of hashes)

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:


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.

Comment on Re: Foreach on an array (of hashes)
Select or Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://42648]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2014-09-21 07:13 GMT
Find Nodes?
    Voting Booth?

    How do you remember the number of days in each month?

    Results (167 votes), past polls