【问题标题】:If I reassigned OUT in Perl 6, how can I change it back to stdout?如果我在 Perl 6 中重新分配了 OUT,如何将它改回标准输出?
【发布时间】:2017-11-15 22:08:18
【问题描述】:

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

我希望一个块中的所有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";

【问题讨论】:

  • 编辑澄清 - 因为标题不应仅描述您所询问的主题或主题,而应描述实际问题本身
  • 如果不是 $*OUT 而是你想临时覆盖的其他变量,你会怎么做?
  • 也许看看我在this comment 中链接到的模块之一中的代码会有所帮助。
  • @CharlesDuffy 好多了,谢谢!霍利,很好的解决方案。谢谢。

标签: raku


【解决方案1】:

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

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

【讨论】:

  • 第二个例子不应该使用given而不是with吗?因为如果块将包含真正的代码,它应该出错(双关语不是故意的)而不是被静默地跳过。
  • @Holli Brad 的早期示例是自动安全的。他们在作用域之后重置旧的$*OUT,即使代码抛出异常。这通常是一个非常好的习惯。您不能搞砸(例如,如果同事将早期的 return 添加到函数中)。
  • @piojo 我想把它写成with $fh-foo {…} else -&gt; $failure {…}
猜你喜欢
  • 2017-07-19
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2016-05-24
相关资源
最近更新 更多