Course of Raku / Objects, I/O, and exceptions / Input and output / Working with files / Exercises / Save and read
Solution: Save and read
Here is a possible solution to the task.
Code
spurt 'number.txt', "42\n";
my $n = slurp('number.txt').trim.Int;
say $n * 2;🦋 You can find the source code in the file save-and-read.raku.
Output
84Comments
spurtcreates the file and writes the string to it;slurpreads the whole file back into a string. Together they are a complete save-and-load round trip.What comes back from
slurpis text —"42\n"— so wetrimoff the trailing newline and call.Intto turn it into a number before doing arithmetic. The result,42 * 2, is84.The program still works without
.trim.Intthough.
Course navigation
← Save and read | Build up a log →