Perl 6 Programming/Files
< Perl 6 ProgrammingBefore we begin
Filehandle
Any interaction with files in Perl 6 happens through a filehandle. [note 1] A filehandle is an internal name for an external file. The open
function makes the association between the internal name and the external name, while the close
function breaks that association. Some IO handles are available for your use without the need to create them: $*OUT
and $*IN
are connected to STDOUT and STDIN, the standard output and standard input streams, respectively. You will need to open every other filehandle on your own.
Paths
Always remember, that any path to a file within the program is with respect to the current working directory.
File operations: Text
Open a file for reading
To open a file, we need to create a filehandle to it. This simply means that we create a (scalar) variable which will refer to the file from now on. The two argument syntax is the most common way to call the open
function: open PATHNAME, MODE
—where PATHNAME
is the external name of the file you want opened and MODE
is the type of access. If successful, this returns an IO handle object which we can put into a scalar container:
my $filename = "path/to/data.txt";
my $fh = open $filename, :r;
The :r
opens the file in read-only mode. For brevity, you can omit the :r
—since it is the default mode; and, of course, the PATHNAME
string can be passed directly, instead of passing it via a $filename
variable.
Once we have a filehandle, we can read and perform other actions on the file.
Notes
- ↑ generalized to IO handles for interaction with other IO objects like streams, sockets, etc.