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
3Comments
:outredirects the program’s output into theProcinstead of the screen, and.out.slurp(:close)reads it all back;.trimremoves the trailing newline thatechoadds.Once the output is an ordinary string in our program, we treat it like any other data:
.words.elemssplits it on whitespace and counts the pieces, giving3. This is the point of capturing — the external program becomes a building block whose result we process further.