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

I want to perform something like a:
SELECT department, count(department) FROM table GROUP BY department
.. but on a Perl hash.

Let's say I have something like the following:

use strict; my %testhash = ( 8172263 => { name => 'Robert', department => 'music' }, 8177234 => { name => 'Elizabeth', department => 'chemistry' }, 7226331 => { name => 'Reginald', department => 'chemistry' }, 8117223 => { name => 'Ralph', position => 'King' }, 9118223 => { name => 'Richard', department => 'music' }, 9119233 => { name => 'Pamela', department => 'music' } ); # how do I discover the number of # chemistry students in my hash very quickly? my $musicstudents = grep { $testhash{$_}->{department} && $testhash{$_}->{department} =~ m/music/ } keys %testhash; print( "$musicstudents\n" );

But that's when I know there are music students before hand. How do I build up a hash very quickly containing item counts within a column?

e.g. if I called some (inline maybe) function

my %outputhash = somefunction(\%testhash, 'department');
the output hash would look something like:
# my %outputhash = ( music => 3, # chemistry => 2 );

What I'm looking for is code efficiency here, as I could build this up using lots of loops but would rather not do that.. maybe something fancy with a map is possible but I just can't see it for the moment.

Update: Thanks to Zaxo and ysth for the answer. The precise variant I will use in my code is:
my %outputhash; $outputhash{$_->{department}}++ for grep { $_->{department} } values %testhash;

Embaressingly enough I knew about the keys function but had been unaware of the values function until now.. *picks up Camel book again*

Replies are listed 'Best First'.
Re: Simulating a summary of a hash
by Zaxo (Archbishop) on Jun 02, 2005 at 08:29 UTC

    It's really the regular hash counting problem:

    sub somefunction { my ($hash, $key) = @_; my %outputhash; $outputhash{$_->{$key}}++ for values %$hash; %outputhash; }
    By not checking for truth of $_->{$key}, you get also get a count of missing entries in $outputhash{""} and you don't miss Department Zero if it's spelled 0.

    After Compline,
    Zaxo

Re: Simulating a summary of a hash
by ysth (Canon) on Jun 02, 2005 at 08:25 UTC
    I have the feeling I'm missing a deeper question that you may have, but here's untested code for the surface question:
    sub somefunction { my ($href, $key) = @_; my %counts; $_->{$key} && ++$counts{$_->{$key}} for values %$href; return %counts; }
Re: Simulating a summary of a hash
by thcsoft (Monk) on Jun 02, 2005 at 08:25 UTC
    perldoc -f grep

    language is a virus from outer space.