Input/Output
File-related operations
Here we present a quick overview of the file-related input/output operations. Details can be found in the documentation for the IO role, as well as the IO::Handle and IO::Path types.
Reading from files
One way to read the contents of a file is to open the file via the open
function with the :r
(read) file mode option and slurp in the contents:
my = open "testfile", :r;my = .slurp;.close;
Here we explicitly close the filehandle using the close
method on the IO::Handle
object. This is a very traditional way of reading the contents of a file. However, the same can be done more easily and clearly like so:
my = "testfile".IO.slurp;# or in procedural form:= slurp "testfile"
By adding the IO
role to the file name string, we are effectively able to refer to the string as the file object itself and thus slurp in its contents directly. Note that the slurp
takes care of opening and closing the file for you.
Line by line
Of course, we also have the option to read a file line-by-line. The new line separator (i.e., $*IN.nl-in
) will be excluded.
for 'huge-csv'.IO.lines -># or if you'll be processing latermy = 'huge-csv'.IO.lines;
Writing to files
To write data to a file, again we have the choice of the traditional method of calling the open
function – this time with the :w
(write) option – and printing the data to the file:
my = open "testfile", :w;.print("data and stuff\n");.close;
Or equivalently with say
, thus the explicit newline is no longer necessary:
my = open "testfile", :w;.say("data and stuff");.close;
We can simplify this by using spurt
to open the file in write mode, writing the data to the file and closing it again for us:
spurt "testfile", "data and stuff\n";
By default all (text) files are written as UTF-8, however if necessary, an explicit encoding can be specified via the :enc
option:
spurt "testfile", "latin1 text: äöüß", enc => "latin1";
To write formatted strings to a file, use the printf function of IO::Handle.
my = open "testfile", :w;.printf("formatted data %04d\n", 42);.close;
To append to a file, specify the :a
option when opening the filehandle explicitly,
my = open "testfile", :a;.print("more data\n");.close;
or equivalently with say
, thus the explicit newline is no longer necessary,
my = open "testfile", :a;.say("more data");.close;
or even simpler with the :append
option in the call to spurt
:
spurt "testfile", "more data\n", :append;
To explicitly write binary data to a file, open it with the :bin
option. The input/output operations then will take place using the Buf
type instead of the Str
type.
Copying, renaming, and removing files
Routines copy
, rename
, move
, and unlink
are available to avoid low-level system commands. See details at copy, rename, move, and unlink. Some examples:
my = 'foo';my = 'foo.bak';my = '/disk1/foo';# note 'diskN' is assumed to be a physical storage devicecopy , ; # overwrites $fileb if it existscopy , , :createonly; # fails if $fileb existsrename , 'new-foo'; # overwrites 'new-foo' if it existsrename , 'new-foo', :createonly; # fails if 'new-foo' exists# use move when a system-level rename may not workmove , '/disk2/foo'; # overwrites '/disk2/foo' if it existsmove , '/disk2/foo', :createonly; # fails if '/disk2/foo' existsunlink ;.IO.unlink;
The two unlink
sentences remove their argument if it exists, unless the user does not have the correct permissions to do so; in that case, it raises an exception.
Checking files and directories
Use the e
method on an IO::Handle
object to test whether the file or directory exists.
if "nonexistent_file".IO.eelse
It is also possible to use the colon pair syntax to achieve the same thing:
if "path/to/file".IO ~~ :e
my = "path/to/file";if .IO ~~ :e
Similarly to the file existence check, one can also check to see if a path is a directory. For instance, assuming that the file testfile
and the directory lib
exist, we would obtain from the existence test method e
the same result, namely that both exist:
say "testfile".IO.e; # OUTPUT: «True»say "lib".IO.e; # OUTPUT: «True»
However, since only one of them is a directory, the directory test method d
will give a different result:
say "testfile".IO.d; # OUTPUT: «False»say "lib".IO.d; # OUTPUT: «True»
Naturally the tables are turned if we check to see if the path is a file via the file test method f
:
say "testfile".IO.f; # OUTPUT: «True»say "lib".IO.f; # OUTPUT: «False»
There are other methods that can be used to query a file or directory, some useful ones are:
my = "file";say .IO.modified; # return time of last file (or directory) changesay .IO.accessed; # return last time file (or directory) was readsay .IO.s; # return size of file (or directory inode) in bytes
See more methods and details at IO::Path.
Getting a directory listing
To list the contents of the current directory, use the dir
function. It returns a list of IO::Path objects.
say dir; # OUTPUT: «"/path/to/testfile".IO "/path/to/lib".IO»
To list the files and directories in a given directory, simply pass a path as an argument to dir
:
say dir "/etc/"; # OUTPUT: «"/etc/ld.so.conf".IO "/etc/shadow".IO ....»
Creating and removing directories
To create a new directory, simply call the mkdir
function with the directory name as its argument:
mkdir "newdir";
The function returns the name of the created directory on success and Nil
on failure. Thus the standard Perl idiom works as expected:
mkdir "newdir" or die "$!";
Use rmdir
to remove empty directories:
rmdir "newdir" or die "$!";