in reply to Perl Sum & Count column based data
Perhaps the following will be helpful:
use strict; use warnings; my $base = 0; my @cols = qw/2 3/; my %hash; while ( my $line = <DATA> ) { 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 .. $#co +ls; 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
Output when $col = 0; @cols = qw/2 3/:
U1 3 337 3 630 U2 1 150 1 375 U3 1 100 1 600 U9 1 137 1 200
Output when $col = 1; @cols = qw/2 4 5/:
ID1 3 337 3 150 3 650 ID2 2 250 2 500 2 425 ID3 1 137 1 75 1 150
The while loop builds a data structure like the following, which is then later printed in the for loop:
$VAR1 = { 'U1' => [ 337, 630, 3 ], 'U2' => [ 150, 375, 1 ], 'U9' => [ 137, 200, 1 ], 'U3' => [ 100, 600, 1 ] };
Edit: Updated to more closely meet the OP's scalability specs.
|
|---|