2016-04-13 58 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