一个非常简单的问题,但我不能轻易找到答案.
我希望所有人都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)
简单的答案是只能在词汇上改变它
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)