【问题标题】:Perl : Store Print Outputs of a function without Changing the functionPerl:存储函数的打印输出而不更改函数
【发布时间】:2017-10-10 09:46:25
【问题描述】:

我有一个子程序:

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

我需要把上面子程序打印出来的数据放到一个文件里。

PS:我无法更改函数变量,我唯一能做的就是访问函数。

【问题讨论】:

标签: perl file-io


【解决方案1】:

当您打印到“默认文件句柄”而不是显式打印到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";

【讨论】:

    【解决方案2】:

    好的,您真正想要的是在调用函数之前将 STDOUT 重定向到文件,然后再将其重定向回来:

    # open filehandle log.txt
    open (my $LOG, '>>', 'log.txt');
    
    # select new filehandle
    select $LOG;
    
    application();
    
    # restore STDOUT
    select STDOUT;
    

    【讨论】:

    • 用文件句柄交换 STDOUT 的任何其他方式?在我目前的情况下,select 将被视为一个无法识别的函数,因为我正在处理 perl 的混合形式的文件。
    【解决方案3】:

    你可以重新打开STDOUT(不过你需要先关闭它)。

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

    所有这些都在open() 的文档中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2020-02-11
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      相关资源
      最近更新 更多