如何在Perl中打印变量而不是文件?

Pau*_*han 8 printing perl

如何使用Perl打印到变量?

我一直在研究一个程序,它以高度冗长的方式记录它的迭代进度......

print $loghandle $some_message;
Run Code Online (Sandbox Code Playgroud)

但是,我还想有选择地将一些消息打印到不同的文件中.当然,我可以将代码撒上......

print $loghandle $some_message
print $otherloghandle $some_message
Run Code Online (Sandbox Code Playgroud)

或者将整个业务重写为一个功能.等等.

我想要做的是在打开$ loghandle时做一些魔术,这样当我print正在进行时,我实际上只是sprintf对一个变量进行ish操作(调用它$current_iteration),这样当我做出决定时我能做点什么......

print $real_log_file $current_iteration;
print $other_real_log_file $current_iteration if($condition);
Run Code Online (Sandbox Code Playgroud)

我很确定我在某个地方见过这样的东西,但我不知道它在哪里或在哪里看.

编辑:File :: Tee在某种程度上在*nix上解决了这个问题,但我在Windows上运行.

Eth*_*her 19

您可以open通过它将标量变量视为文件句柄:

open my $fh, '>', \$variable or die "Can't open variable: $!";
print $fh "Treat this filehandle like any other\n";
Run Code Online (Sandbox Code Playgroud)

您甚至可以将stdout或stderr映射到标量:

close STDOUT;
open STDOUT, '>', \$variable or die "Can't open STDOUT: $!";
Run Code Online (Sandbox Code Playgroud)

如果您想分割输出或设置配置文件以便在日志记录中执行"有趣"的操作,那么最好使用其他人建议的Log4Perl.


And*_*ett 5

你的意思是IO :: Scalar吗?允许您使用文件句柄语义写入变量.

  • 您不需要显式地使用IO :: Scalar.open()本身就可以正常工作. (3认同)