Help with converting Python script to Perl for CSV sort
I was able to code a rough application in Python for sorting; however, I find coding in Perl more reward able for some strange reason. Due to the latter, I want to create a similar solution in Perl.
However, I am having a hard time understanding a number of examples I have already found.
http://stackoverflow.com/questions/4221424/perl-sort-csv-on-a-certain-column sorting CSV files
If someone has the time, could they whip up a comparable solution, and explain each section? Would it matter if I wanted to sort by number in field 1 or by alpha characters in field 2? Can the same code be used for both?
Example: from link 512942
#!/usr/bin/perl my $sheet; my $count = -1; while( <DATA> ) { chomp; $count++; # skip header next unless $count; my $row; @$row = split( /,/, $_ ); push @$sheet, $row; } foreach my $row ( sort { $a->[1] <=> $b->[1] } @$sheet ) { print join( ',', @$row ), "\n";
I am not understanding the sort in the “foreach” loop… is this regex ? Should I focus on learning REGEX in Perl better? Just need some direction and pointers. To be honest, I feel so lost that I am not even sure how to articulate my questions; however, I want to keep learning Perl even if I find it difficult.
My Python app
import csv field = 1 data = [] with open('input.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: data.append(row) def getKey(item): return item[field] sorted = sorted(data, key=getKey) f = open('output.csv','w') for i in sorted: s = ",".join(i) f.write(s + '\n') f.write(s + '\n')
Example of CSV file, which is only used for example
Thank you1,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
In reply to Help with converting Python script to Perl for CSV sort by jasonwolf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |