Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Adding an array to an existing csv file as a new column

by haukex (Archbishop)
on Jul 13, 2018 at 14:12 UTC ( [id://1218447]=note: print w/replies, xml ) Need Help??


in reply to Adding an array to an existing csv file as a new column

Please use <code> tags to format your code fix your <code> tags, see How do I post a question effectively? and Markup in the Monastery.

But based on your problem description, here is a template that reads two CSV files of the same length in parallel and writes to a third (which you can then use to replace the second file, if you like) - I think this is what you're after? You can adjust the logic for creating the new rows to fit your needs. It uses Text::CSV, and you should also install Text::CSV_XS for speed.

use warnings; use strict; use Data::Dumper; # Debug $Data::Dumper::Useqq=1; use Text::CSV; my $file1 = 'in1.txt'; my $file2 = 'in2.txt'; my $outfile = 'out.txt'; my $csv = Text::CSV->new({binary=>1, auto_diag=>2, eol=>$/}); open my $ifh1, '<', $file1 or die "$file1: $!"; open my $ifh2, '<', $file2 or die "$file2: $!"; open my $ofh, '>', $outfile or die "$outfile: $!"; $csv->getline($ifh1); # read and discard header $csv->getline($ifh2); # read and discard header $csv->print($ofh, ['col1','col2']); # new header while ( my $row1 = $csv->getline($ifh1) ) { my $row2 = $csv->getline($ifh2); die "file1 has more lines than file2" unless $row2; # do whatever you like to create the output row here my $orow = [@$row1, @$row2]; # example: join the two rows print Dumper($row1, $row2, $orow); # Debug $csv->print($ofh, $orow); } die "file2 has more lines than file1" unless eof($ifh2); close $ifh1; close $ifh2; close $ofh; $csv->eof or $csv->error_diag;

Minor edits.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1218447]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-23 23:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found