简体   繁体   English

我们如何在perl中向csv文件中添加列?

[英]How can we add columns to a csv file in perl?

My first and second CSV file contain the following data. 我的第一个和第二个CSV文件包含以下数据。 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. 现在我想将第二个文件的数据插入到第一个文件中,以便我将数据显示在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);
}

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM