in reply to 'group by query' from array of hashes

I think you need to use the syntax that forces types to arrays and hashes. It's in the Hashes of Arrays section of Chapter 9, Data Structures in the Camel book.

my %queries_by_key = (); # Hash of arrays my $number_of_queries = scalar @all_queries; for (my $i = 0 ; $i < $number_of_queries; ++$i) { my %query = %{ pop @all_queries }; # value of pop() is a hash foreach my $query_key (keys %query) { # Treat each value in %queries_by_key as an anonymous array push @{ $queries_by_key{$query_key} }, $query{$query_key}; } } foreach my $key (sort keys %queries_by_key) { print "$key has "; print join ',', @{ $queries_by_key{$key} }; # treat as an array print "\n"; }

I tried to make this clear, but the syntax is kinda confusing. Hopefully they'll explain it better in the book.

Hope this helps,

Chris

Replies are listed 'Best First'.
Re^2: 'group by query' from array of hashes
by Jim (Curate) on Jan 29, 2011 at 16:36 UTC

    Here's my refactoring of chayashida's fine illustration:

    #!perl use strict; use warnings; my @all_queries; # Array of hashes my %queries_by; # Hash of arrays push @all_queries, { foo => 20 }; push @all_queries, { bar => 30 }; push @all_queries, { foo => 10 }; push @all_queries, { zen => 90 }; push @all_queries, { zen => 1 }; for my $query (@all_queries) { my ($query_key, $query_value) = %$query; push @{ $queries_by{$query_key} }, $query_value; } for my $query_key (sort keys %queries_by) { my @query_values = sort { $a <=> $b } @{ $queries_by{$query_key} } +; my $query_values = join ',', @query_values; print "$query_key has $query_values\n"; } __END__ bar has 30 foo has 10,20 zen has 1,90