2012-01-11 72 views
2

我正在編譯一個Perl程序,我正在將輸出STDOUT寫入一個文件。在同一個程序中,我想在STDOUT的輸出上使用while函數運行另一個小腳本。所以,我需要將第一個腳本的輸出保存到數組中,然後我可以在@array>中使用它。像STDOUT到數組Perl

open(File,"text.txt"); 
open(STDOUT,">output,txt"); 
@file_contents=<FILE>; 

foreach (@file_contents){ 

//SCRIPT GOES HERE// 

write; 
} 
format STDOUT = 
VARIABLE @<<<<<< @<<<<<< @<<<<<< 
      $x  $y  $z 
. 

//Here I want to use output of above program in while loop // 

while(<>){ 

} 

我怎麼能第一個程序的輸出保存到數組,這樣我可以在while循環使用,或者我如何能直接在while循環使用STDOUT。我必須確保第一部分完全執行。提前致謝。

+0

我想你是在這裏走了一條糟糕的道路。如果您需要在同一個程序中進一步處理數據,使用perlform可能不是最好的選擇。 – TLP 2012-01-11 15:42:55

回答

0

我假設你想重新打開STDOUT以使write函數起作用。但是,正確的解決方案是指定文件句柄或使用select

write FILEHANDLE; 

select FILEHANDLE; 
write; 

不幸的是,它似乎的perlform的IO有點神祕,似乎並沒有允許詞法文件句柄。

你的問題是你不能在程序中重複使用格式化文本,所以需要一些三元編程。你可以做的是打開一個打印到標量的文件句柄。這是另一個有點神祕的Perl功能,但在這種情況下,它可能是直接執行此操作的唯一方法。

# Using FOO as format to avoid destroying STDOUT 
format FOO = 
VARIABLE @<<<<<< @<<<<<< @<<<<<< 
      $x  $y  $z 
. 

my $foo; 
use autodie; # save yourself some typing 
open INPUT, '<', "text.txt"; # normally, we would add "or die $!" on these 
open FOO, '>', \$foo;  # but now autodie handles that for us 
open my $output, '>', "output.txt"; 

while (<FILE>) { 
    $foo = "";   # we need to reset $foo each iteration 
    write FOO;   # write to the file handle instead 
    print $output $foo; # this now prints $foo to output.txt 
    do_something($foo); # now you can also process the text at the same time 
} 

正如你會發現,我們現在先打印格式化的行標$foo。雖然它在那裏,但我們可以將它作爲常規數據處理,因此不需要保存到文件並重新打開它以獲取數據。

每次迭代,數據連接到$foo的末尾,所以爲了避免積累,我們需要重置$foo最好的方式來處理這將是在範圍內使$foo詞彙,但不幸的是我們需要$foo聲明在while循環之外,以便能夠在open語句中使用它。

可能在while循環內部可以使用local $foo,但我認爲這是對這個已經非常糟糕的黑客攻擊添加更多不良做法。

結論:

有了這一切說和做,我懷疑來處理,這是在其他一些方式不使用perlform可言,和格式化數據的最佳方式。雖然perlform可能非常適合打印到文件,但它並不適合您的想法。我從前面回憶起這個問題,也許還有其他答案會更好。如使用sprintf,如Jonathan suggested

0

假設從你的第一個程序的輸出是製表符分隔:

while (<>) { 
    chomp $_; 
    my ($variable, $x, $y, $z) = split("\t", $_); 
    # do stuff with values 
}  
6

既然你重新映射標準輸出,因此寫入一個文件,你大概可以關閉STDOUT,然後重新打開文件進行讀取。

相當你要發送任何其他輸出的地方有點神祕,但想必你可以解決這個問題。如果是我,我不會擺弄STDOUT。我會做劇本寫的文件句柄:

use strict; 
use warnings; 

open my $input, "<", "text.txt" or die "A horrible death"; 
open my $output, ">", "output.txt" or die "A horrible death"; 
my @file_contents = <$input>; 
close($input); 

foreach (@file_contents) 
{ 
    # Script goes here 
    print $output "Any information that goes to output\n"; 
} 
close $output; 

open my $reread, "<", "output.txt" or die "A horrible death"; 

while (<$reread>) 
{ 
    # Process the previous output 
} 

的使用注意事項詞法文件句柄,在檢查的open工作中,close當輸入文件,使用use strict;use warnings;完成。 (我只用Perl工作了20年,我知道我不相信我的腳本,直到他們用這些設置運行乾淨。)