用perl将两个TXT文件合成一个csv文件?

2025-04-13 13:05:05
推荐回答(1个)
回答1:

举个例子
write_file("t1.txt", "aa\tbb\ncc\tdd\n");
write_file("t2.txt", "mm\tnn\noo\tpp\n");
my $m = read_file('t1.txt');
my $n = read_file('t2.txt');
my $str;
for (0..$#$m) {$str .= join(",", @{$m->[$_]}, @{$n->[$_]}) . "\n";}
write_file('t.csv', $str);

sub write_file {
open (my $h, '+>', shift) || exit;
print $h shift;
close $h;
}

sub read_file {
open (my $h,  shift) || exit;
my @arr;
while (<$h>) {
chomp;
push @arr, [split("\t", $_)];
}
return [@arr];
}