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*


In reply to Simulating a summary of a hash by monarch

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.