Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

raku

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";
like image 905
Eugene Barsky Avatar asked Nov 15 '17 22:11

Eugene Barsky


1 Answers

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";
like image 98
Brad Gilbert Avatar answered Sep 26 '22 22:09

Brad Gilbert