http://qs321.pair.com?node_id=1196147


in reply to perl group by and sort from a csv input file

Hi gowthamvels,

one typical way is to use a hash as an accumulator. The hash keys should be the two first values of your CSV input, and the hash values should accumulate the third value of your CSV.

At the end, you can just print out the hash in your desired format.

For example, something like this:

use strict; use warnings; use feature 'say'; my %hash; while (<DATA>) { chomp; my ($id, $num, $val) = split /,/, $_; $hash{"$id,$num"} += $val; } for my $key (sort keys %hash) { say "$key,$hash{$key}"; } __DATA__ 3211111,100,3.2 3211112,101,3.2 3211111,100,1.2 3211112,100,2.2 3211113,100,5.2 3211112,100,0.3

Replies are listed 'Best First'.
Re^2: perl group by and sort from a csv input file
by gowthamvels (Novice) on Aug 01, 2017 at 06:59 UTC

    Thanks a lot for your great help and response.

    Apologies, As I am new to the perl monks, I dodnt know the rules as I didnt paste my code which I tried. from next time I will follow the same.

    I have used the below code

    use strict; use warnings; use feature 'say'; my %hash; while (<DATA>) { chomp; my ($id, $num, $val) = split /,/, $_; $hash{"$id,$num"} += $val; } for my $key (sort keys %hash) { say "$key,$hash{$key}"; }

    Thanks a ton for all of you for this great help.