my @a = read_file($file1)
or die "couldn't read $file1 - $!";
my @b = read_file($file2)
or die "couldn't read $file2 - $!";
my $combined = {}; # hashref
my $i=0;
foreach (@a) {
chomp;
$combined->{$i}{b} = '' unless defined $combined->{$i}{b};
$combined->{$i++}{a} = $_;
}
$i=0;
foreach (@b) {
chomp;
$combined->{$i}{a} = '' unless defined $combined->{$i}{a};
$combined->{$i++}{b} = $_;
}
foreach my $i (sort {$a<=>$b} keys %$combined) {
print $combined->{$i}{a}, ("\t" x 2), $combined->{$i}{b}, "\n";
}
答案 0 :(得分:4)
据我了解,您可以同时读取两行文件的一行,并打印用制表符分隔的每一行,如:
use warnings;
use strict;
die unless @ARGV == 2;
open my $fha, q|<|, $ARGV[0] or die;
open my $fhb, q|<|, $ARGV[1] or die;
while ( my $a = <$fha>, my $b = <$fhb> ) {
chomp( $a, $b );
printf qq|%s\t\t%s\n|, $a, $b;
}
如果文件的行数不同,则此脚本无效。对于这种情况,您将需要另一种方法。
答案 1 :(得分:2)
您只需在shell中执行此操作:cat file1.txt file2.txt file3.txt > selected.txt
或者在Perl中:
use strict;
@ARGV = ('file1.txt', 'file2.txt', 'file3.txt');
open MULTI, '>', 'selected.txt'
or die $!;
while (<>) {
print MULTI;
}
答案 2 :(得分:2)
怎么样:
#!/usr/bin/perl
use strict;
use warnings;
my @files = qw(file1 file2 file3 file4);
my %content;
my $max_rec = 0;
foreach (@files) {
open my $fh, '<', $_ or die $!;
@{$content{$_}} = <$fh>;
chomp @{$content{$_}};
close $fh;
$max_rec = @{$content{$_}} if scalar(@{$content{$_}}) > $max_rec;
}
open my $fh, '>', 'outfile' or die $!;
for my $i (0 .. $max_rec) {
my $out = '';
foreach (@files) {
$out .= defined($content{$_}[$i]) ? $content{$_}[$i] : '';
$out .= "\t\t" unless $_ eq $files[-1];
}
print $fh $out,"\n";
}
输入文件:
$ cat file1
1.1
$ cat file2
2.1
2.2
$ cat file3
3.1
3.2
3.3
$ cat file4
4.1
4.2
4.3
4.4
输出文件:
$ cat outfile
1.1 2.1 3.1 4.1
2.2 3.2 4.2
3.3 4.3
4.4
答案 3 :(得分:0)
此脚本专注于IO :: File的高性能,仅适用于同一行中至少有一些非空白文本的文件。
#!/usr/bin/perl
use IO::File;
@f= map { IO::File->new($_) } @ARGV;
print $q,qq(\n) until ($q=join (qq(\t), map { m{(.*)} && $1 } map { $_->getline } @f))=~m{^\t+$}