用于写入和读取的Perl文件处理程序

时间:2016-04-13 19:09:49

标签: perl file

我正在尝试将cmd的输出写入文件并grep输出输出中的模式并将其推送到数组中(如果找到)。我在将输出写入文件时面临问题

以下代码不使用文件处理程序,数组工作正常并打印输出

my $output = `cmd to get output`;
print "output is : $output\n";   

但是如果我将相同的代码放在文件处理程序中,那么它甚至不会打印硬编码的单词output is :

use warnings;
use strict;
use Data::Dumper;

 foreach my $cfg_file (@cfg_files){
 #open the file handler for both read and write mode
  open my $fh1, '+>', 'c:\TEMP\cfg.txt' or die $!;
   while ( <$fh1> ) { 
    my $output = `cmd to get output using $cfg_file`;
    print "output is : $output\n";
    print $fh1 $output;   #write the output into file

    if (/$pattern/) {   #read the file for a specific pattern
           print "$_";
         push(@matching_lines, $_);        
    }
  }
}
 print Dumper(\@matching_lines); 

代码甚至没有抛出警告。我得到的输出就是 $VAR1 = [];

1 个答案:

答案 0 :(得分:2)

while (<$fh1>)尝试从$fh1文件句柄中读取。它根本没有任何东西,循环体永远不会被执行。顺便说一句,+>首先破坏了文件,因此当代码到达while时,文件确实是空的。

您可以放弃while循环并针对您刚刚获得的变量$pattern测试$output

open my $fh1, '+>', 'c:\TEMP\cfg.txt' or die $!;

my $output = `cmd to get output`;
print "output is : $output\n";
print $fh1 $output;   #write the output into file

if ($output =~ /($pattern)/s) {  # test and capture from output
     print "$1\n";
     push (@matching_lines, $1);        
}

由于输出可能有多行,我们将/s添加到正则表达式。

您的其余代码将是相同的。

相关问题