c.con has asked for the wisdom of the Perl Monks concerning the following question:
I am looking to add an array to a csv file as a column. I basically have to csv files containing a column of numbers. There csv files have 100,000's of lines. Example:
What I want to do is take columns from 2 different csv files, subtract the 2nd from the 1st and then add a new column to the 2nd file with a column called difference and the result. So far, I have got as far as creating an array with the difference in it. I am having trouble to actually put this array back as a column into the 2nd file. Does anyone have any suggestions. I want to keep the code I've written thus far if possible though. I was able to add the array of values to the end of the csv file but not after each line.Time1 1 2 3 Time 2 4 5 6
use 5.10.0; use warnings; my $output = "results.txt"; my ($fh1, $fh2, $fh3, $fh4, $fh5); my ($file1, $file2) = @ARGV; my (@col1, @col2, @col3); my ($lines, $lines2, $lines3); my (@array, @array2) = (); my @diff = (); my $csv = "csv.csv"; ###Open files for read and write### open ($fh1, '<', $file1) or die $!; open ($fh2, '+<', $file2) or die $!; open ($fh3, '>', $output) or die $!; #open my $out, ">", "out.csv" or die $!; ###Reads lines from file into an array### while ($lines = <$fh1>){ chomp $lines;#Removes the new line @col = split "," , $lines; #Array where each index holds the dat +a of each column push @array, $col[5]; #adding element to the array containing sl +ack values for file } shift @array;#Removes the header line from the array -i.e column name ###Reads lines from file into an array### while ($lines2 = <$fh2>){ print $fh4 $lines2; chomp $lines2; #push @list, $lines2; @col2 = split "," , $lines2; push @arr, @col2; push @array2, $col2[5]; } shift @array2; ###Iterates through the array and finds the difference in slack### foreach my $i (@array){ $diffs = $array2[$i] - $array[$i];#Variable showing difference push @diff, $diffs;#Adding element to an array containing the diff +erence values } ###Prints out the 2 differenct slacks from each run and shows the diff +erence between them. #print $fh3 "Difference :", $array[$_] ,"-", $array2[$_], " = ", $diff +[$_], "\n" for 1 .. $#array; unshift @diff, "Difference";
2018-07-14 Athanasius fixed closing code tag and added code tags around data
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Adding an array to an existing csv file as a new column
by haukex (Archbishop) on Jul 13, 2018 at 14:12 UTC | |
|
Re: Adding an array to an existing csv file as a new column
by Athanasius (Archbishop) on Jul 15, 2018 at 03:40 UTC |