Course of Raku / Objects, I/O, and exceptions / Input and output / File handles / Exercises / Pass a handle to a function
Solution: Pass a handle to a function
Here is a possible solution to the task.
Code
sub log-line($fh, $message) {
$fh.say($message);
}
my $fh = open 'log.txt', :w;
log-line($fh, 'started');
log-line($fh, 'working');
log-line($fh, 'done');
$fh.close;
print slurp 'log.txt';🦋 You can find the source code in the file pass-a-handle.raku.
Output
started
working
doneComments
The handle returned by
openis just a value held in$fh, so it can be passed tolog-lineas an argument like any string or number. Inside the subroutine,$fh.saywrites through that same open handle.Because the handle stays open across all three calls, each
log-lineappends another line to the same file.closethen flushes everything, andslurpreads the three lines back.This is what makes handles composable: a function can accept a handle and write to (or read from) it without caring which file it points at — the caller decides that when it opens the file.