http://www.perlmonks.org?node_id=30630

v has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

I'm creating a hash that contains IP_Address:Size objects. The same IP_Address occurs many times, as is Size. i want to know the following:

Originally posted as a Categorized Question.

  • Comment on How do I extract the number of times a value appears in a hash?

Replies are listed 'Best First'.
Re: How do I extract the number of times a value appears in a hash?
by BlaisePascal (Monk) on Sep 01, 2000 at 00:53 UTC
    Is the "IP_Address:size" blocks the hash values, or the hash keys?

    Assuming the the IP_Address:size blocks are the hash values (say, you were keying off of a connection ID, or something), then you could do something like:

    my %counts; my %sizes; for (values %inhash) { my ($ip, $size) = split /:/; next unless defined $ip; $counts{$ip}++; $sizes($ip)+= $size; } for $ip (keys $counts) { my ($count, $size) = ($counts{$ip},$sizes{$ip}; print "IP Address $ip appeared $count times, for a total size of $si +ze\n"; }
    Does that help?
Re: How do I extract the number of times a value appears in a hash?
by ton (Friar) on Apr 05, 2001 at 01:06 UTC
    Assuming that "IPaddr:Size" are the values:
    map {if /^(.*):(\d*)$/ {$count{$1}++;$size{$1}+=$2;}} values(%hash);
    This will place results in the %count and %size hashes, keyed by IP address. If "IPaddr:Size" are the keys, just replace the 'values' with 'keys' in the fragment above.
Re: How do I extract the number of times a value appears in a hash?
by dsb (Chaplain) on Jan 24, 2001 at 02:41 UTC
    Pardon the building of the hash
    #! /usr/bin/perl %hash = ( '1' => 'foo', '2' => 'bar', '3' => 'foo', '4' => 'foo', ); %count; foreach $key ( keys %hash ) { $val = $hash{$key}; $count{$val}++; } foreach $key1 ( keys %count ) { print $key1 . " appears " . $count{$key1} . " times\n"; }