Course of Raku / Objects, I/O, and exceptions / Input and output / Running external programs 🆕 / Exercises / Pass a variable to a child
Solution: Pass a variable to a child
Here is a possible solution to the task.
Code
my $file = 'notes.txt';
spurt $file, "one\ntwo\nthree\n";
%*ENV<NOTES> = $file;
my $proc = shell 'wc -l < "$NOTES"', :out;
say $proc.out.slurp(:close).trim;
unlink $file;🦋 You can find the source code in the file read-env.raku.
Output
3Comments
spurtcreatesnotes.txtwith three lines. Setting%*ENV<NOTES>to its name puts the file name into the environment that any child program will inherit.The
shellcommand inherits that environment, expands$NOTEStonotes.txt, and feeds the file intowc -l, which counts its lines. The< "$NOTES"redirection keeps the output to just the number3, which we capture with:outand trim.Finally the clean-up is done back in Raku with
unlink— no shell needed. Deleting the file is a plain file-system operation, so there is no reason to launch another process for it.