首页 > 解决方案 > 如何在使用“使用严格”时将 STDOUT 分配给 var 并打印到该变量?

问题描述

linux 上的 perl-5.24.0-gcc620

我在 perl 模块中有一些现有代码,它使用 IO::Tee 将标准输出定向到文件和终端......

use strict;
use IO::Tee;
our $tee;

sub common {
    open $tee, ">", "my.log";
    $tee = new IO::Tee(\*STDOUT, $tee);
    etc... 
}
.
.
.
sub some_sub {
    print $tee "I want this to go to the log file and the terminal. Works fine.\n";
}

现在,我想使用 perl 脚本来使用“some_sub”,该脚本不运行执行 IO::Tee 的“common” sub。所以 $tee 将是未定义的,当我尝试使用它时会出现编译错误。

我做的黑客是...

if($tee) {
    print $tee "I want to print this\n";
} else { 
    print "I want to print this";
} 

但是打印语句到处都是,我想要一种更优雅的方式来处理这个问题。我想做的是这样的......

if(!($tee)) {
    $tee = STDOUT;
}

...然后保留所有现有的“print $tee ...”语句。
但这给了我一个简单的错误,因为我使用的是“使用严格”......

Bareword "STDOUT" not allowed while "strict subs" in use at ./change_tee_STDOUT.pl line 4.

如果我摆脱“使用严格”,它似乎工作。

如何在保留 "use strict" 的同时获得 "$tee = STDOUT" 的功能?我觉得也许有一种方法可以将 STDOUT 转换为文件句柄类型,或者类似的东西。我接近了吗?

标签: perl

解决方案


$tee = \*STDOUT;      # Reference to a glob containing the IO object.

或者

$tee = *STDOUT;       # Glob containing the IO object.

或者

$tee = *STDOUT{IO};   # Reference to the IO object.

我用第一个。(而且您在现有代码中也做得很好!)第二个应该也能正常工作。我不确定最后一个是否受到普遍支持。(Perl 本身不会有任何问题,但是 XS 模块呢?)


推荐阅读