如果我在Perl 6中重新分配OUT,我怎么能把它改回到stdout?

Eug*_*sky 5 perl6

一个非常简单的问题,但我不能轻易找到答案.

我希望所有人都say在一个块中去一个文件.但后来我希望我的输出返回STDOUT.怎么做?

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";
Run Code Online (Sandbox Code Playgroud)

Bra*_*ert 8

简单的答案是只能在词汇上改变它

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";
Run Code Online (Sandbox Code Playgroud)
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";
Run Code Online (Sandbox Code Playgroud)

如果您必须解决其他人的代码,您可以像首先打开它一样重新打开它.

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";
Run Code Online (Sandbox Code Playgroud)

  • 为什么这么复杂?为什么不只是我的$ stdout = $ * STDOUT; .... $ * STDOUT = $ stdout; (2认同)