Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Just another Perl shrine
 
PerlMonks  

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

by v (Initiate)
on Aug 31, 2000 at 20:39 UTC ( [id://30630]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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:
  • how many times each IP_Address appears
  • sum of Size for any given IP_Address

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 Aug 31, 2000 at 20: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 dsb (Chaplain) on Jan 23, 2001 at 21: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"; }
Re: How do I extract the number of times a value appears in a hash?
by ton (Friar) on Apr 04, 2001 at 21: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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://30630]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.