Karthick S
Karthick S

Reputation: 3304

In perl, how do I find the sum of values in 2nd column grouped by values in the first column

I am writing a perl script and am getting the values after many operations as follows:

'John', 10, .20
'John', 20, .05
'Paul', 50, .10
'Joe', 70, .03
'Joe', 12, .30

Now, I need to do the following operations:

  1. Sum up the value of column 2 grouped by column 1.
  2. Multiply column 2 by column 3 and find the sum of those answers again grouped by Column 1.

I am trying to see if this can only be accomplished by converting this array into a hash based on the first column or if there is a better way to do this.

Please note that this is not a homework exercise. I have tried to simplify the data by giving masking the original values. The values are of the type given above.

Expected Output:

'John', 30, 0.1
'Paul', 50, 0.1
'Joe',  82, 0.06

Upvotes: 0

Views: 311

Answers (1)

Karthick S
Karthick S

Reputation: 3304

Figured out the answer while trying to "clean" it for posting here:

My code that works:

while (<FILE>)
{
    chomp($_);
    my ($name, $count, $percent) = split("\t");
    $hash{$name}{"count"} += $count;
    if ($count != 0)
    {
        $sonar_out_hash{$name}{"value"} += $percent * $count / 100;
    }
}

Thanks to @KrishnachandraSharma for insisting that I post.

Upvotes: 2

Related Questions