Forum Moderators: coopster & phranque

Message Too Old, No Replies

An array of hash references

         

Robber

4:19 pm on Dec 2, 2002 (gmt 0)

10+ Year Member



I have an array containing hash references. To get a single value out is no problem eg:

foreach $result (@results) {

print $result->{"xyz"};
}

But if I want to nest a loop to iterate over all keys in the hash, sounds simple, but whats the answer?

Cheers

seindal

4:37 pm on Dec 2, 2002 (gmt 0)

10+ Year Member



Do you mean something like:

print join('', map { $_->{xyz} } @results);

It'll concatenate all the 'xyz' values from the array of hashrefs.

René.

Robber

4:38 pm on Dec 2, 2002 (gmt 0)

10+ Year Member



Dont panic guys - managed to answer my own question (this time!), if anyone is interested it goes something like this:

foreach $result (@results) {
foreach $field (keys %$result){
print "$result->{$field}";
print "<br>";
}
}

Robber

4:40 pm on Dec 2, 2002 (gmt 0)

10+ Year Member



Hi seindal,

thanks for helping - we posted at the same time, as you can see above, I got things sorted - but your suggestion seems interesting, whats going on in there, what does map do?

andreasfriedrich

4:48 pm on Dec 2, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



map BLOCK LIST evaluates BLOCK for each element of LIST locally setting $_ to each element and returns the list value coposed of the results of each such evaluation.

foreach $result (@results) {  
foreach $field (keys %$result){
print "$result->{$field}";
print "<br>";
}
}

could be written as

map 
{$result = $_; print map
{ "$result->{$_}<br>" } keys %$_} @results;

or better

map 
{$result = $_; print join '<br>', map
{ $result->{$_} } keys %$_} @results;

Andreas

seindal

4:53 pm on Dec 2, 2002 (gmt 0)

10+ Year Member



Hi,

map runs through a list, performs something on each element, and returns a new list of the resulting values.

Inside the code part of map, $_ represents the active element from the input list. It is a reference, so the list can be changed, also inadvertently, by changing $_.

This code takes an array of strings and returns an array of the lengths:

@lengths = map { length } @strings;

This adds a final . to all elements missing it:

map { /\.$/ or $_ .= '.' } @array;

I use it all the time because it makes very compact code. It is quite readable for experienced perl programmers, probably less so for the less experienced programmers and for those without knowledge of functional programming.

map is described in the perlfunc manual page.

René.

Robber

6:37 pm on Dec 2, 2002 (gmt 0)

10+ Year Member



Thanks both for that, looks good.