perl - 如何在使用“使用严格”时将 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 转换为文件句柄类型,或者类似的东西。我接近了吗?
解决方案
$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 模块呢?)
推荐阅读
- reactjs - React Native:如何在模拟器上复制错误信息?
- swift - 如何快速加载本地主机
- android - 自定义 Android 应用
- python - 有没有办法使用python烧瓶和MongoEngine将字典列表插入mongodb而不使用for循环?
- vue.js - NuxtJS i18n [vue-router] 名为 about_us___en 的路由不存在
- pyomo - 为什么 ipopt 没有正确优化 - 非线性站点分配?
- laravel - 我有一个来自另一台设备的项目,当我尝试在我的设备中安装时出现错误
- admob - 有价值的库存框架网站
- flutter - 在 setState 上更新 UI 时出现颤振问题
- python - 使用 urllib3 和 python 2.7 从 url 下载 .txt 文件?