使用Perl从2个文件中逐行打开和读取

时间:2012-07-05 17:55:20

标签: perl file printing

我正在尝试在Perl中逐行打印2个不同的文件。这是什么语法? 代码:

#1. Initialize: log file path and ref Log file path
use strict;
use warnings;
my $flagRef="true";
my $logPath="C:/ExecutionSDKTest_10.2.2/Logs/${ARGV[0]}.log";
my $refLogPath="C:/ExecutionSDKTest_10.2.2/Logs/${ARGV[1]}_Ref.properties.txt";
#print log file path followed by reflog path: P
#print "$logPath\n$refLogPath\n";

#2. Traverse log file and refLog file to replace ALL instances of:
#"hr:min:sec" with "xx:xx:xx" 
open INLOG, $logPath or die $!;
open INREF, $refLogPath or die $!;

#equiv: >>$logLine=readline(*FHLOG);        
#$logLine= <FHLOG>;
#$refLine= <FHREF>;
while (<INLOG>) #syntax
{
   print "$_";
   #I'd like to print lines from INREF too! :)
   #Syntax?
 }

4 个答案:

答案 0 :(得分:3)

这可以使用paste(1)轻松解决。说a.txt包含:

a1
a2
a3

和b.txt包含:

b1
b2
b3

然后:

$ paste -d '\n' a.txt b.txt
a1
b1
a2
b2
a3
b3
$ 

稍微长一点的Perl单行程也是如此:

$ perl -e '@fhs=map { open my $fh, "<", $_; $fh } @ARGV; while (!$done) { $done=1; map { $v=<$_>; do { print $v; $done=0 } if (defined $v); } @fhs; }' a.txt b.txt
a1
b1
a2
b2
a3
b3
$ 

展开它并将其重写为正确的脚本留给读者练习。

答案 1 :(得分:2)

这是一个简单的脚本,可以满足您的要求:

#!/usr/bin/perl
use strict;

open FILE1,'<file1';
open FILE2,'<file2';

my @arr1 = <FILE1>;
my @arr2 = <FILE2>;

if(@arr1 > @arr2) {
    print_arrs(\@arr1,\@arr2);
}
else {
    print_arrs(\@arr2,\@arr1);
}

sub print_arrs {
    my ($arr1,$arr2) = @_;
    for(my $k = 0; $k < @{$arr1}; $k++) {
        print @{$arr1}[$k];
        print @{$arr2}[$k] if @{$arr2}[$k];
    }
}

它可能不是最优雅的解决方案,但它可以满足您的要求!

答案 2 :(得分:1)

通常更好的做法是在while循环中处理文件,而不是将它们全部读入内存。

该程序根据您的要求交替显示两个文件中的行。

use strict;
use warnings;

my $logPath = sprintf 'C:/ExecutionSDKTest_10.2.2/Logs/%s.log', shift;
my $refLogPath = sprintf 'C:/ExecutionSDKTest_10.2.2/Logs/%s_Ref.properties.txt', shift;

open my $inlog, '<', $logPath or die qq(Unable to open "$logPath": $!);
open my $inref, '<', $refLogPath or die qq(Unable to open "$refLogPath": $!);

do {
  print if defined($_ = <$inlog>);
  print if defined($_ = <$inref>);
} until eof $inlog and eof $inref;

答案 3 :(得分:0)

另一种更像问题中使用方式的方式是:

use strict;
use warnings;

open( my $h1, '<', 'a.txt' );
open( my $h2, '<', 'b.txt' );

for(;;)
{
    my $x    = <$h1>;
    my $y    = <$h2>;
    defined($x) || defined($y)
        or last;
    print $x // '';
    print $y // '';
}