mirage_zz has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am new to perl and need your help on this problm: I have an Array of hashes which looks like this
$var = [ { "D1" => 1, "D2" => 2 }, { "D2" => 5, "D3" => 6 }, ];
I need the sum of matching D's in both the arrays. Output should be a single associative array as shown below:
$var = ( "D1" => 1, "D2" => 7 "D3" => 6 )
It would be great if the above array were sorted based on the values:
$var = ( "D2" => 7 "D3" => 6 "D1" => 1, )
Kindly help. Rgds.

Replies are listed 'Best First'.
Re: Urgent Help: Array of Hashes
by ikegami (Patriarch) on Sep 26, 2007 at 23:45 UTC
    my $var = [ { "D1" => 1, "D2" => 2 }, { "D2" => 5, "D3" => 6 }, ]; my %combined; foreach my $subhash (@$var) { foreach my $key (keys %$subhash) { $combined{$key} += $subhash->{$key}; } } my @sorted_keys = sort { $combined{$b} <=> $combined{$a} } keys %combined; foreach my $key (@sorted_keys) { print("$key: $combined{$key}\n"); }

    You can't actually "sort the associative array", but you can control the order in which the data is accessed. That's what @sorted_keys is about.

      Hi, Thank you for the reply. Rgds
Re: Urgent Help: Array of Hashes
by merlyn (Sage) on Sep 26, 2007 at 23:39 UTC
      Hi, I am building a small search utility, and the D's in the array are documents. The values are frequency of words in each document. The final array, just contains a summary of documents and the total occurences Rgds
        You can conveniently store the counts of particular "words" using a hash:
        #!/usr/bin/env perl use strict; use warnings; my %freqs = (); # .... # for each match of $word $freqs{$word}++; # ... # the list the counts: foreach my $word (keys(%freqs)) { print "$word: $freqs{$word}\n"; } 1;