如何在 Perl 中打印到变量而不是文件? [英] How can I print to a variable instead of a file, in Perl?

查看:74
本文介绍了如何在 Perl 中打印到变量而不是文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Perl 打印到变量?

How can I print to a variable with Perl?

我一直在开发一个程序,该程序以非常详细的方式记录其迭代进度......

I've been working on a program for a while which logs its iterative progress in a highly verbose fashion...

print $loghandle $some_message;

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

However, I'd like to also selectively print some of the messages to a different file. Naturally, I could sprinkle the code with...

print $loghandle $some_message
print $otherloghandle $some_message

或者把整个业务改写成一个函数.废话.

Or rewrite the whole business into a function. Blah.

我想做的是在打开 $loghandle 时做一些魔术,这样当我 print'ing 时,我实际上只是在做一个 sprintfish 对变量的操作(称之为 $current_iteration),这样当我进入决策点时,我可以做这样的事情......

What I want to do is do some magic when I open the $loghandle so that when I'm print'ing, I'm actually just doing a sprintfish operation against a variable(call it $current_iteration), so that when I get down to a decision point I can do something like this...

print $real_log_file $current_iteration;
print $other_real_log_file $current_iteration if($condition);

我很确定我在某处看到过类似的东西,但我不知道它在哪里或在哪里看.

I'm fairly sure I've seen something like this somewhere, but I have no idea where it is or where to look.

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

edit: File::Tee solves this problem to some extent on *nix, but I run on Windows.

推荐答案

您可以通过 打开:

You can treat a scalar variable as a filehandle by opening it:

open my $fh, '>', \$variable or die "Can't open variable: $!";
print $fh "Treat this filehandle like any other\n";

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

You can even map stdout or stderr to a scalar:

close STDOUT;
open STDOUT, '>', \$variable or die "Can't open STDOUT: $!";

如果你想分割你的输出或设置一个配置文件来用你的日志做有趣"的事情,你最好使用 Log4Perl 正如其他人所建议的那样.

If you want to split your output or set up a config file to do "interesting" things with your logging, you are better off with Log4Perl as others have suggested.

这篇关于如何在 Perl 中打印到变量而不是文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆