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

Hello gowthamvels and welcome to the monastery and to the wonderful world of Perl!

Next time please show the code you tried: generally monks prefere (with reason) to see some effort from the wisdom seeker.

You already got wise answers and smart ones too. Mine is a oneliner (be aware of windows double quotes: use single quote on Linux).

perl -F"," -lanE "$h{join ',',@F[0,1]}+=$F[2]}{map{say $_.','.$h{$_}}s +ort keys %h" sample.csv 3211111,100,4.4 3211112,100,2.5 3211112,101,3.2 3211113,100,5.2

See perlrun to know how many useful switches and parameter you can feed to Perl!

Basically speaking -a autosplits incoming strings (at spaces), feeding the special @F array (see perlvar for it)

-F specify an alternative pattern for the autosplit

-l uses a smart line handling

-n wraps your program into a while loop without printing his input ( -p also print it)

-E executes the following code and import some feature (like say I used). Normally you can use -e

}{ is a trick: see eskimo greeting

If the oneliner seems overhelming for you, use -MO=Deparse to have it expanded:

perl -MO=Deparse -F"," -lanE "$h{join ',',@F[0,1]}+=$F[2]}{map{say $_. +','.$h{$_}}sort keys %h" sample.csv BEGIN { $/ = "\n"; $\ = "\n"; } BEGIN { $^H{'feature_unicode'} = q(1); $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } LINE: while (defined($_ = <ARGV>)) { chomp $_; our(@F) = split(/,/, $_, 0); $h{join ',', @F[0, 1]} += $F[2]; } { map {say $_ . ',' . $h{$_};} sort(keys %h); } -e syntax OK

If you are really lazy you can learn what switches do using MO=Deparse adding them progressively and seeing what happens executing a noprogram ( is what perl -e 1 is, marked by '???' in the deparsed output):

perl -MO=Deparse -e 1 '???'; -e syntax OK perl -MO=Deparse -n -e 1 LINE: while (defined($_ = <ARGV>)) { '???'; } -e syntax OK perl -MO=Deparse -n -a -e 1 LINE: while (defined($_ = <ARGV>)) { our(@F) = split(' ', $_, 0); '???'; } -e syntax OK perl -MO=Deparse -n -a -F"," -e 1 LINE: while (defined($_ = <ARGV>)) { our(@F) = split(/,/, $_, 0); '???'; } -e syntax OK perl -MO=Deparse -n -a -F"," -l -e 1 BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = <ARGV>)) { chomp $_; our(@F) = split(/,/, $_, 0); '???'; } -e syntax OK perl -MO=Deparse -n -a -F"," -l -E 1 BEGIN { $/ = "\n"; $\ = "\n"; } BEGIN { $^H{'feature_unicode'} = q(1); $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } LINE: while (defined($_ = <ARGV>)) { chomp $_; our(@F) = split(/,/, $_, 0); '???'; } -e syntax OK

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.