Course of Raku / Objects, I/O, and exceptions / Input and output / Running external programs 🆕 / Exercises / Capture the output

Solution: Capture the output

Here is a possible solution to the task.

Code

my $proc = run 'echo', 'hello world raku', :out;
my $output = $proc.out.slurp(:close).trim;
say $output.words.elems;

🦋 You can find the source code in the file capture-output.raku.

Output

3

Comments

  1. :out redirects the program’s output into the Proc instead of the screen, and .out.slurp(:close) reads it all back; .trim removes the trailing newline that echo adds.

  2. Once the output is an ordinary string in our program, we treat it like any other data: .words.elems splits it on whitespace and counts the pieces, giving 3. This is the point of capturing — the external program becomes a building block whose result we process further.

Course navigation

Capture the output   |   Check the exit code