Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing a module output

Tags:

io

raku

Say we have this module:

unit module outputs;

say "Loaded";

And we load it like this

use v6;

use lib ".";

require "outputs.pm6";

That will print "Loaded" when it's required. Say we want to capture the standard output of that loaded module. We can do that if it's an external process, but there does not seem to be a way for redirecting *OUT to a string or,if that's not possible, to a file. Is that so?

like image 955
jjmerelo Avatar asked Feb 24 '19 20:02

jjmerelo


People also ask

What are module outputs?

A module output is a variable in the module that contains information generated by the module and that can supply a value to other connected variables or modules.


2 Answers

You could try use IO::String:

use v6;
use lib ".";
use IO::String;

my $buffer = IO::String.new;
with $buffer -> $*OUT {
    require "outputs.pm6";
};

say "Finished";
print ~$buffer;

Output:

Finished
Loaded

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

like image 50
Håkon Hægland Avatar answered Sep 30 '22 19:09

Håkon Hægland


Temporarily reassigning $*OUT so that .print calls append to a string:

my $capture-stdout;

{ 
  my $*OUT = $*OUT but
             role { method print (*@args) { $capture-stdout ~= @args } }

  require "outputs.pm6" # `say` goes via above `print` method 
}

say $capture-stdout; # Loaded
like image 34
raiph Avatar answered Sep 30 '22 17:09

raiph