use strict; use warnings; my $base = 0; my @cols = qw/2 3/; my %hash; while ( my $line = ) { my @vals = split ' ', $line; $hash{ $vals[$base] }[$_] += $vals[ $cols[$_] ] for 0 .. $#cols; $hash{ $vals[$base] }[ $#cols + 1 ]++; } for my $key ( sort keys %hash ) { print "$key"; print "\t$hash{$key}[ $#cols + 1 ]\t$hash{$key}[$_]" for 0 .. $#cols; print "\n"; } __DATA__ U1 ID1 100 280 30 350 U1 ID1 137 250 70 200 U2 ID2 150 375 400 50 U1 ID2 100 100 100 375 U3 ID1 100 600 50 100 U9 ID3 137 200 75 150 #### U1 3 337 3 630 U2 1 150 1 375 U3 1 100 1 600 U9 1 137 1 200 #### ID1 3 337 3 150 3 650 ID2 2 250 2 500 2 425 ID3 1 137 1 75 1 150 #### $VAR1 = { 'U1' => [ 337, 630, 3 ], 'U2' => [ 150, 375, 1 ], 'U9' => [ 137, 200, 1 ], 'U3' => [ 100, 600, 1 ] };