CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
how to merge duplicate values in hash?

 



alferic
Novice

Oct 10, 2013, 1:35 AM

Post #1 of 3 (313 views)
how to merge duplicate values in hash? Can't Post

i have this data contained in a file

BIN COUNT
1 20
2 0
2 1
3 0
3 0
3 1
7 0
8 2
9 1
9 2
10 3

I split this and stored in a hash

$hash{seq++} = {
BIN => $bin_num,
COUNT => $count,
};

I wanted to merge the duplicate BINs into one and sum up their values (counts). The output would look like this:

BIN COUNT
1 20
2 1
3 1
7 0
8 2
9 3
10 3

I was able to loop through hash using foreach and display it but cannot proceed with my desired output. I don't know how to do it. Please help!


Zhris
User

Oct 10, 2013, 3:23 AM

Post #2 of 3 (309 views)
Re: [alferic] how to merge duplicate values in hash? [In reply to] Can't Post

Hi,

This takes the original input data and produces the expected output data. It does not generate the interim hash structure that you provided in your post (which may be desirable or not).


Code
#!/usr/bin/perl 
use strict;
use warnings FATAL => qw/all/;

my %hash;

open my $fh, '<', 'input.txt' or die "cannot open: $!";
#my $header = <$fh>; # uncomment if "BIN COUNT" header.
while ( my $line = <$fh> )
{
chomp $line;
my ($bin, $count) = split /\s+/, $line;
$hash{$bin} += $count;
}
close $fh;

print "$_, $hash{$_}\n" foreach ( sort { $a <=> $b } keys %hash);


Chris


(This post was edited by Zhris on Oct 10, 2013, 3:25 AM)


alferic
Novice

Oct 10, 2013, 5:09 AM

Post #3 of 3 (300 views)
Re: [Zhris] how to merge duplicate values in hash? [In reply to] Can't Post

Hello Chris!

This is pure genius!

Thanks a lot!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives