If I reassigned OUT in Perl 6, how can I change it back to stdout?

坚强是说给别人听的谎言 提交于 2019-12-06 02:26:46

问题


A very simple question, but I can't easily find an answer.

I want all say in a block to go to a file. But then I want my output to return to STDOUT. How to do that?

my $fh_foo = open "foo.txt", :w;
$*OUT = $fh_foo;
say "Hello, foo! Printing to foo.txt";

$*OUT = ????;
say "This should be printed on the screen";

回答1:


The simple answer is to only change it lexically

my $fh-foo = open "foo.txt", :w;
{
  my $*OUT = $fh-foo;
  say "Hello, foo! Printing to foo.txt";
}

say "This should be printed on the screen";
my $fh-foo = open "foo.txt", :w;

with $fh-foo -> $*OUT {
  say "Hello, foo! Printing to foo.txt";
}

say "This should be printed on the screen";

If you have to work around someone else's code you could reopen it the same way it was opened in the first place.

my $fh-foo = open "foo.txt", :w;
$*OUT = $fh-foo;
say "Hello, foo! Printing to foo.txt";

$*OUT = IO::Handle.new( path => IO::Special.new('<STDOUT>') ).open();

say "This should be printed on the screen";


来源:https://stackoverflow.com/questions/47318139/if-i-reassigned-out-in-perl-6-how-can-i-change-it-back-to-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!