2016-04-13 55 views
0

我正在尝试将cmd的输出写入文件,并在输出中为模式写入grep,并将其推送到数组中(如果找到)。我现在面临的问题在输出写入文件用于写入和读取的Perl文件处理程序

下面的代码没有文件处理程序的使用,阵列工作正常,并打印输出

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); 

的代码是不是连抛警告.The输出我得到的只是 $VAR1 = [];

+1

你实际上并没有使用'@ cfg_files'循环的处理方式是什么?这些是你想要阅读的文件吗? –

+1

它被称为*文件句柄*,而不是*文件处理程序*。它允许你保持某种东西,而不是处理某些东西。 – ikegami

回答

2

while (<$fh1>)试图从$fh1文件句柄中读取。它根本没有任何文件,循环体从不执行。顺便提一句,+>首先破坏文件,所以文件确实是空的,因为代码到达while

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

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的正则表达式。

其余的代码将是相同的。

+0

完美。虽然循环是我犯的错误。 – Jill448

+0

我在'cmd中使用$ cfg_file来获取输出。但现在删除while循环后,我得到错误'在模式匹配中使用未初始化的值$ _(m //)'我是否需要在写入之后和读取之前重新打开while循环? – Jill448

+0

我没有看到你建议的循环中的变化。现在我没有收到错误 – Jill448