In IO::Handle§
See primary documentation in context for method WRITE.
method WRITE(IO::Handle:D: Blob:D \data --> Bool:D)
Called whenever a write operation is performed on the handle. Always receives the data as a Blob
, even if a textual writing method has been called.
class IO::Store is IO::Handle { has @.lines = []; submethod TWEAK { self.encoding: 'utf8'; # set up encoder/decoder } method WRITE(IO::Handle:D: Blob:D \data --> Bool:D) { @!lines.push: data.decode(); True; } method gist() { return @!lines.join("\n" ); } } my $store = IO::Store.new(); my $output = $PROCESS::OUT; $PROCESS::OUT = $store; .say for <one two three>; $PROCESS::OUT = $output; say $store.lines(); # OUTPUT: «[one two three]»
In this example we are creating a simple WRITE
redirection which stores anything written to the filehandle to an array. Se need to save the standard output first, which we do in $output
, and then everything that is print
ed or said (through say
) gets stored in the defined IO::Store
class. Two things should be taken into account in this class. By default, IO::Handle
s are in binary mode, so we need to TWEAK
the objects if we want them to work with text. Second, a WRITE
operation should return True
if successful. It will fail if it does not.