monarch has asked for the wisdom of the Perl Monks concerning the following question:
.. but on a Perl hash.SELECT department, count(department) FROM table GROUP BY department
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
the output hash would look something like:my %outputhash = somefunction(\%testhash, 'department');
# 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.
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 | |
Re: Simulating a summary of a hash
by ysth (Canon) on Jun 02, 2005 at 08:25 UTC | |
Re: Simulating a summary of a hash
by thcsoft (Monk) on Jun 02, 2005 at 08:25 UTC |