How can I use tie() to redirect STDOUT, STDERR only for certain packages?

*爱你&永不变心* 提交于 2019-12-06 07:59:31

Aside from fixing the libraries, I can think of only one solution that might be better.

You can re-open STDOUT and STDERR file handles into your own file handles. Then, re-open STDOUT and STDERR with your tied handles.

For example, here's how you do it for STDOUT:

open my $fh, ">&", \*STDOUT or die "cannot reopen STDOUT: $!";
close STDOUT; 

open STDOUT, ">", "/tmp/test.txt"; 

say $fh "foo"; # goes to real STDOUT
say "bar";     # goes to /tmp/test.txt

You can read perldoc -f open for all the gory details on what ">&" and such does.

Anyway, instead of "/tmp/test.txt" you can replace that open call with the setup for your tied file handle.

Your code will have to always use an explicit file handle to write or use select to switch file handles:

select $fh;
say "foo"; # goes to real STDOUT

select STDOUT;
say "bar"; # goes to /tmp/test.txt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!