2017-10-10 111 views
0

我有一個子程序:的Perl:存儲打印功能的輸出不改變功能

sub application(**arguments**) 
{ 
     print ("found the black ship"); 
     # many more print statements. 
     return 18000; 
} 

我需要通過在文件上面的子程序打印的數據。

PS:我不能改變函數變量,只有我能做的事情是訪問函數。

+0

Perl不支持的論點就像你在這裏暗示,除非你有一個非常新的Perl和方式的函數定義[了'signatures'功能開啓(https://perldoc.perl.org/ perlsub.html#簽名)。 – simbabque

回答

1

確定你真正想要的是調用函數之前STDOUT重定向到一個文件,然後重定向回算賬:

# open filehandle log.txt 
open (my $LOG, '>>', 'log.txt'); 

# select new filehandle 
select $LOG; 

application(); 

# restore STDOUT 
select STDOUT; 
+0

任何其他方式交換標準輸出與文件句柄?正如我目前的情況,選擇將被視爲一個無法識別的函數,因爲Iam正在處理一個混合形式的perl文件。 – vikram9866

1

您可以重新打開STDOUT(你需要關閉它第一次雖然) 。

close STDOUT; 
open STDOUT, '>>', 'somefile.txt' or die $!; 
application(...); 

這些都在open()的文檔中。

2

在打印到「默認文件句柄」時,而不是明確指向STDOUT,您可以在調用該方法之前調用select。沒有必要亂用STDOUT文件句柄。

my $output = ''; 
open my $capture, '>', \$output; 
my $old_fh = select $capture; 

application(...); 

select $old_fh; # restore default file handle, probably STDOUT 
close $capture; 
print "The output of application() was: $output\n";