如何在Perl中关闭并重新打开STDOUT? [英] How can close and reopen STDOUT in Perl?
问题描述
我想关闭STDOUT以防止我的代码输出需要进一步计算但又不想在我的网页上显示的特定图像。
I'd like to close STDOUT to prevent my code from outputing a particular image that I need for further computation but do not want on my web page.
所以我想关闭STDOUT,执行我的代码操作,然后重新打开STDOUT以将内容输出到网页。 (不保存文件)
So i want to close STDOUT, do what I have to do with my code, then reopen STDOUT to output stuff to a web page. (Not to a file)
我尝试过的是:
close STDOUT;
# my code here
open STDOUT;
这不起作用...
谢谢
推荐答案
有几种方法可以解决您的问题,其中许多方法不需要您关闭STDOUT并承担风险
There are several ways to approach your problem, and many of them do not require you to close STDOUT and risk fubaring your program's standard I/O channels.
例如,您可以使用(1-arg) select
命令可将 print
命令的输出临时定向到其他地方
For example, you can use the (1-arg) select
command to direct the output of print
commands somewhere else temporarily.
print $stuff_you_want_to_send_to_STDOUT;
select(NOT_STDOUT);
# now default print sends things to NOT_STDOUT.
# This doesn't need to be a real filehandle, though you may get warning
# messages if it is not.
...;
print $the_image_you_dont_want_to_go_to_STDOUT;
...;
select(STDOUT);
# now print sends things to STDOUT agin
print $more_stuff_you_do_want_to_go_to_STDOUT;
您还可以重新分配 * STDOUT
*OLD_STDOUT = *STDOUT;
print $for_STDOUT;
*STDOUT = *NOT_STDOUT; # again, doesn't need to be a real filehandle
print $stuff_to_suppress;
*STDOUT = *OLD_STDOUT; # restore original STDOUT
print $more_stuff_for_STDOUT;
这篇关于如何在Perl中关闭并重新打开STDOUT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!