http://qs321.pair.com?node_id=539758

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

I've got some data in a database table like this:
[cams] users> SELECT *, DAY(stats_date) as stats_day FROM stream_updat +e_stats_daily WHERE MONTHNAME(stats_date)='March' AND YEAR(stats_date +)=2006 ORDER BY DAY(stats_date) LIMIT 3\G *************************** 1. row *************************** stats_date: 2006-03-01 diary_entries: 2 photos_uploaded: 0 videos_uploaded: 0 stream_questions: 0 msgs: 12 date_entered: 2006-03-27 17:32:28 messages_received: NULL stats_day: 1 *************************** 2. row *************************** stats_date: 2006-03-02 diary_entries: 7 photos_uploaded: 0 videos_uploaded: 0 stream_questions: 0 msgs: 4 date_entered: 2006-03-27 17:35:43 messages_received: NULL stats_day: 2 *************************** 3. row *************************** stats_date: 2006-03-03 diary_entries: 2 photos_uploaded: 0 videos_uploaded: 0 stream_questions: 0 msgs: 2 date_entered: 2006-03-27 17:42:10 messages_received: NULL stats_day: 3 3 rows in set (0.01 sec) [cams] users>

and I have the ability to turn this data into a Perl array of hashrefs, with one array element for database row:

@ar = ( { stats_date => '2006-03-01', diary_entries => 2, msgs => 12, stats_d +ay => 1}, { stats_date => '2006-03-02', diary_entries => 7, msgs => 4,. stats_d +ay => 2}, { stats_date => '2006-03-03', diary_entries => 3, msgs => 2,. stats_d +ay => 3}, );

But the issue is, I need a hashref of arrays so that this data can be properly displayed:

{ diary_entries => [ 2, 7, 3], msgs => [ 12, 4, 2] }
I thought there was a CPAN module that did this sort of thing but I can't recall the name of it.

Replies are listed 'Best First'.
Re: Converting an array of hashrefs into a hashref of arrays
by ikegami (Patriarch) on Mar 28, 2006 at 17:45 UTC
    my %by_fields; #while (my $row = $sth->fetchrow_hashref()) { foreach my $row (@ar) { foreach my $field (keys %$row) { my $value = $row->{$field}; push(@{$by_fields{$field}}, $value); } }
Re: Converting an array of hashrefs into a hashref of arrays
by bowei_99 (Friar) on Mar 28, 2006 at 20:56 UTC
    I think the module you may be referring to is Data::Dumper, although it tends to format it a little differently. You could have something like:

    use Data::Dumper; ...your code here ... print Dumper($ref);
    where $ref is a reference to your data structure, in this case, a hash of arrays.

    It's included by default on at least perl 5.6 and above; maybe even earlier versions, so you shouldn't have to install it.

    -- Burvil