Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: perl group by and sort from a csv input file

by Laurent_R (Canon)
on Jul 27, 2017 at 08:28 UTC ( #1196147=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1196147]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2023-05-29 06:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?