perl代码合并多个文本文件

前端之家收集整理的这篇文章主要介绍了perl代码合并多个文本文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有多个文本文件.我已编写代码通过 shell输入2个文件并合并它们.但我如何合并多个文件.系统命令是有用的.

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";
}

解决方法

据我所知,您可以同时读取两行文件的一行,并打印用制表符分隔的每一行,如:

use warnings;
use strict;

die unless @ARGV == 2;

open my $fha,q|<|,$ARGV[0] or die;
open my $fhb,$ARGV[1] or die;

while ( my $a = <$fha>,my $b = <$fhb> ) { 
    chomp( $a,$b );
    printf qq|%s\t\t%s\n|,$a,$b; 
}

如果文件具有不同的行数,则此脚本将不起作用.对于这种情况,您将需要另一种方法.

猜你在找的Perl相关文章