2013-03-27 81 views
0

我正在尋找一種方法來減少某些腳本中的某些print混亂。我想要一些輸出到一個文件,一些到屏幕,一些到兩個。這是讓我無法迴避的「一部分」。有沒有辦法打開一個FILEHANDLE這將去STDOUT和一個文件已經open ed?打印重定向到多個輸出目標

事情是這樣的:

open ($file_only, ">", "$logfile"); 
open ($file_and_term, .....); 


print $file_and_term "Nice stuff for the user to see\n"; 
print $file "$some_command\n"; 
print $file `$some_command`; 
$debug && print $file "some debug info goes here, too\n"; 
print "Hey, good job! You're done!\n" 

我的目標是,該送送$file_and_term行不會雙線,一個去$file和一個去到stdout。也可以根據調試級別使其更具動態性,也許使用由調試級別控制的select語句。


所以,在寫上面,我沒有拿出一個適合我的需要,但不是我的願望的解決方案。 :)所以我會發布這個問題,而我實施我不同的優雅的解決方案。


最後我做這個....這是因爲附近沒有好的地方作爲普通print,但我卻看後,它更強大的....

sub printit { 
    my ($opt, $text) = @_; 
    if ($opt == $FILE || $opt == $BOTH) {print $LOG $text} 
    if ($opt == $TERM || $opt == $BOTH) {print $text} 
}  
+0

http://stackoverflow.com/questions/10519779/perl-redirect-stdout-to-two-files – 2013-03-27 16:47:12

+0

我有Perl 5.8.8。我沒有IO :: Tee,File :: Tee或PerlIO:Util。另外,我的腳本需要在Unix和Windows平臺上工作。 – 2013-04-02 22:38:49

回答

0

至於建議由an answer to an earlier question ,你可以使用IO::Tee

my ($file, $file_and_term); 
open $file, '>', $logfile; 
$file_and_term = IO::Tee->new($file, \*STDOUT); 
+1

實際上有更早的使用[IO :: Tee](http://p3rl.org/IO::Tee)的[答案](http://stackoverflow.com/questions/5392598)。 – 2013-03-28 15:45:58

+0

我有Perl 5.8.8。我沒有IO :: Tee,File :: Tee或PerlIO:Util。另外,我的腳本需要在Unix和Windows平臺上工作。 – 2013-04-04 14:47:16

+0

@Stacey Robert Greenstein - 然後安裝它們。 [他們幾乎運行Perl的每個版本和平臺](http://matrix.cpantesters.org/?dist=IO-Tee+0.64)。 – mob 2013-04-04 15:25:31