ScottJohn has asked for the wisdom of the Perl Monks concerning the following question:
Hi, I am fairly new to Perl and am running into a problem that I hope the Perl Monks can help shed some light on.
I am trying to add a column to an existing file with hundreds of columns and hundreds of thousands of rows. For what it's worth, these files have the same number of rows. The rows also correspond to each other. The file which I am appending a single column has the line number in the first column. (I am appending the second column.)
The following code that works, but it takes forever and I will need to do this daily. I am sure there are several inefficiencies and it seems there has to be a faster way.
Thanks in advance!use warnings; use strict; open (OUTFILE, ">outfile.csv"); open (IN1, "<infile1.csv"); my $counter = 0; while (<IN1>){ chomp; print OUTFILE $_; open (IN2, "<infile2.csv"); while (<IN2>){ my @f = split(/,/); if ($counter == $f[0]){ print OUTFILE ",$f[1]\n"; }} close IN2; $counter = $counter + 1; } close IN1; close OUTFILE;
Scott
Thanks for all the help. To clarify, the numbered file was in order.
This is the code that seemed to work best (similar to jwkrahn's code).
use warnings; use strict; open my $in2, '<', 'infile2.csv' or die "Cannot open 'infile2.csv' bec +ause: $!"; my %data; while ( <$in2> ) { my ( $key, $value ) = split /,/; $data{ $key } = $value; } close $in2; open my $outfile, '>', 'outfile.csv' or die "Cannot open 'StatsCubeR2f +ormat.csv' because: $!"; open my $in1, '<' , 'infile1.csv' or die "Cannot open 'infile1.csv' be +cause: $!"; while ( <$in1> ) { chomp; print $outfile "$_"; if ( exists $data{ $. - 1 } ) { print $outfile ",$data{$. - 1}\n"; } else { print $outfile ",field_name\n"; } } close $in1; close $outfile;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Merging larges files by columns
by lidden (Curate) on Sep 16, 2011 at 21:04 UTC | |
by Kc12349 (Monk) on Sep 16, 2011 at 21:06 UTC | |
|
Re: Merging larges files by columns
by aaron_baugher (Curate) on Sep 16, 2011 at 21:19 UTC | |
by Marshall (Canon) on Sep 17, 2011 at 02:04 UTC | |
by aaron_baugher (Curate) on Sep 17, 2011 at 11:53 UTC | |
by Marshall (Canon) on Sep 19, 2011 at 00:59 UTC | |
|
Re: Merging larges files by columns
by BrowserUk (Patriarch) on Sep 16, 2011 at 21:11 UTC | |
|
Re: Merging larges files by columns
by repellent (Priest) on Sep 17, 2011 at 06:49 UTC | |
|
Re: Merging larges files by columns
by pvaldes (Chaplain) on Sep 16, 2011 at 21:11 UTC | |
|
Re: Merging larges files by columns
by jwkrahn (Abbot) on Sep 17, 2011 at 02:41 UTC | |
|
Re: Merging larges files by columns
by Kc12349 (Monk) on Sep 16, 2011 at 20:54 UTC | |
|
Re: Merging larges files by columns
by Anonymous Monk on Sep 19, 2011 at 03:31 UTC |