2

我正在尝试在 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

4 回答 4

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
$ 

展开它并将其重写为适当的脚本留给读者作为练习。

于 2012-07-05T18:43:11.750 回答
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];
    }
}

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

于 2012-07-05T18:15:57.380 回答
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;
于 2012-07-06T22:43:50.070 回答
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 // '';
}
于 2012-07-06T22:28:41.983 回答