in reply to Help with converting Python script to Perl for CSV sort

Being the author/maintainer of Text::CSV_XS I cannot resist to show its strength. This is a oneliner in perl :)

$ perl -MText::CSV_XS=csv -wE'csv(in=>[sort{$a->[1]cmp$b->[1]}@{csv(in +=>"test.csv")}])' 7,"Ace hardware","Ace hardware1" 4,"Acme cook book","Acme cook book1" 10,"Attack show","Attack show1" 8,"Baker's dozon","Baker's dozon1" 1,"Beginning C","Beginning C1" 2,"Beginning C++","Beginning C++1" 9,"Jumbo frames","Jumbo frames1" 5,"Jumping Jack Flash","Jumping Jack Flash1" 3,"Python Intro","Python Intro1" 6,Zebra,Zebra1 11,"car 54 where are you","car 54 where are you1" 12,"navy blue","navy blue1" 13,"navy gold","navy gold1" $ cat test.csv 1,Beginning C,Beginning C1 2,Beginning C++,Beginning C++1 3,Python Intro,Python Intro1 4,Acme cook book,Acme cook book1 5,Jumping Jack Flash,Jumping Jack Flash1 6,Zebra,Zebra1 7,Ace hardware,Ace hardware1 8,Baker's dozon,Baker's dozon1 9,Jumbo frames,Jumbo frames1 10,Attack show,Attack show1 11,car 54 where are you,car 54 where are you1 12,navy blue,navy blue1 13,navy gold,navy gold1

The test with whitespace for readability:

$ cat test.pl #!/pro/bin/perl use 5.18.2; use warnings; use Text::CSV_XS qw( csv ); # Read the CSV my $aoa = csv (in => *DATA); # Sort on second column my @srt = sort { $a->[1] cmp $b->[1] } @$aoa; # Output the sorted data as CSV csv (in => \@srt); __END__ 1,Beginning C,Beginning C1 2,Beginning C++,Beginning C++1 3,Python Intro,Python Intro1 4,Acme cook book,Acme cook book1 5,Jumping Jack Flash,Jumping Jack Flash1 6,Zebra,Zebra1 7,Ace hardware,Ace hardware1 8,Baker's dozon,Baker's dozon1 9,Jumbo frames,Jumbo frames1 10,Attack show,Attack show1 11,car 54 where are you,car 54 where are you1 12,navy blue,navy blue1 13,navy gold,navy gold1

FWIW as of this week, Text::CSV also supports this in its pure perl Text::CSV_PP parts. (Yeah!)


Enjoy, Have FUN! H.Merijn