0

My first and second CSV file contain the following data. Now I want to insert the data of second file into the first one so that I will the data as shown in final.csv.

First.csv
e_id,e_sal,e_loc
001,20000,mumbai
002,40000,newyork

Second.csv
e_name,e_mngr
raj verma,vineet kothari
sundar prasad,danney morena

Final.csv
e_id,e_name,e_sal,e_mngr,e_loc
001,raj verma,20000,vineet kothari,mumbai
002,sundar prasad,40000,danney morena,newyork

I am trying with this piece of code. But it appends only.

while (!eof($fh1) and !eof($fh2)) { 
    my $line1 = <$fh1>;
    my $line2 = <$fh2>;
    my @l1 = split /\s+/, $line1;
    my @l2 = split /\s+/, $line2;
    push (@l1, @l2);
}
hmatt1
  • 4,939
  • 3
  • 30
  • 51
Robie Nayak
  • 819
  • 10
  • 18

1 Answers1

2

This might not be the most elegant solution, but it gets the job done, supposing that the format is exactly as specified:

use strict;
use warnings;

open FH, "<First.csv";
open FH2, "<Second.csv";
open OUT, ">Final.csv";
while (my $l = <FH>) {
    my @s1 = split(/,/, $l);
    my @s2 = split(/,/, <FH2>);
    for (my $i = 0; $i < scalar(@s1); $i++) {
        print OUT $s1[$i];
        for (my $j = $i; $j < scalar(@s2); $j++) {
            chomp $s2[$j];
            print OUT ",$s2[$j],";
            last;
        }
    }
}
close OUT;
close FH;
close FH2;
Ry-
  • 218,210
  • 55
  • 464
  • 476
blueygh2
  • 1,538
  • 10
  • 15
  • 2
    Check out this question for best practices for opening files: http://stackoverflow.com/questions/318789/whats-the-best-way-to-open-and-read-a-file-in-perl Also instead of using pastebin, it's usually more helpful to post your code in your answer as a code section. – hmatt1 Mar 08 '14 at 20:50