How to sort csv file with perl

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Trevor W

    #1

    How to sort csv file with perl

    I haven't touched Perl in a while but I ran into a relatively simple parsing problem at work that it would be perfect for. I threw together a program using what I remembered--just want to get comments and see if I'm on the right track:

    Data looks like this:
    Code:
    2010-10-05 09:00:00-1000,1,1012,,
    2010-10-05 09:00:00-1000,2,397,,
    2010-10-05 09:00:00-1000,3,0,,
    2010-10-05 09:00:00-1000,4,165,,
    But what I want is <DT>,1012,397,0 ,165,,

    Pseudocode:
    Code:
    Open the dang file
    Remove trailing comma from each line
    Remove date from every n+1,n+2,n+3 lines
    Remove (1,2,3,4) from every n+1,n+2,n+3 lines
    Take final values from every n+1,n+2,n+3 lines and push it onto the end of every n line
    Replace trailing comma
    Close the dang file
    So what I want to do is open the file, put it into an array, chomp and chop it, split that array into other arrays, loop through and rewrite each array line with the right subcomponents of each array, offset?

    Trial code:
    Code:
    open (DATA,$ARGV[0]); or
    	die("File '$ARGV[0]' does not exist?\n");
    my @lines = <DATA>;
    close DATA or 
    	warn $! ? "Error closing pipe: $!"
    		 "Exit status $? from sort";
    
    	chomp @lines;
    	/ get rid of the second comma after each line /
    	chop @lines;
    	
    	/ break up fields into categories by comma /
    	(@time,@mtu,@watth) = split "," , @lines;
    	
    	/ move every n+2nd, n+3rd, and n+4th power value up to the nth line /
    	$hop = 0;
    	while(@lines) {
    	@lines[$hop] = @time[$hop],@watth[$hop],@watth[$hop+1],@watth[$hop+2],@watth[$hop+3]",,";
    	
    	/ hop 4 at a time /
    	$i+=4;
    	}
    open (OUT,$ARGV[0]);
    
    print OUT @lines;
    Thanks for your help. I would love to get competent with Perl.
Working...