Writing to a stream
In this section, we will examine methods that the IO::Handle
class offers for writing to a stream.
The print function
We will start with the simple print
function. Basically, its usage is obvious. It prints the text to the stream. In the case of standard output, use the bare print
function or the $*IN.print
method. If you work with a file, use its file handle.
The following program creates a file named hello.txt
and writes a string to it.:
my $fh = open 'hello.txt', :w; # Open a file for writing $fh.print('Hello, World'); # Print to the file $fh.close; # Close the file so that the data is saved
If the file already exists, it will be re-written, and all previous contents will be lost. Use the :a
append mode if you need to append new output to an existing file:
my $fh = open 'hello.txt', :a; # Open in append mode $fh.print('!'); # Now the file contains 'Hello, World!' $fh.close;
The close
method closes a file. Actually, this does not need...