Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

easily count instances in a hash array 1

Status
Not open for further replies.

1DMF

Programmer
Jan 18, 2005
8,795
GB
Hello,

I was wondering if there was an easy way to count how many indexes in an array of hashes contain a key equal to a specific value.

a for loop and count mechanism seems clunky, so thought you experts could come up with a one liner ;-)

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
I'm hardly an expert, but here's my stab:
Code:
my %hashthing = ( abc => 1, def =>2, ghi =>3, jkl => 1 );
[b]my $count = grep { $_ eq "1" } values %hashthing ;[/b]
print $count;
Internally, it does all the same thing as a loop mechanism, just that the source code for the count fits on one line.
 
Array of hashes. Sure thing.

Code:
my $count = scalar grep {exists $_->{$key} && $_->{$key} eq $value} @array;

- Miller
 
Spot on! Nice Job MillerH ;-)

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top