如果我在 Perl 6 中重新分配了 OUT,我怎样才能将它改回标准输出?

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

一个非常简单的问题,但我无法轻易找到答案。

我希望一个块中的所有 say 转到一个文件。但后来我希望我的输出为 return 到 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";

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

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";

如果您必须绕过其他人的代码,您可以按照最初打开它的方式重新打开它。

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";