Raku Books / Using Raku / Miscellaneous

97. Reading directory content

Print the file names from the current directory.

Reading a directory can be done using the dir routine defined in the IO::Path class.

say dir();

🖥 This program reads the local environment (files, directories, or the command line), so it runs on your own computer but not in the sandboxed in-browser engine.

This tiny program does not do the task really satisfactory, as the dir routine returns a lazy sequence (an object of the Seq data type) of IO::Path objects.

To get the textual file names, take the path part of an IO::Path object using the path method:

.path.say for dir;

🖥 This program reads the local environment (files, directories, or the command line), so it runs on your own computer but not in the sandboxed in-browser engine.

The code is equivalent to the more verbose fragment:

for dir() -> $file {
    say $file.path;
}

🖥 This program reads the local environment (files, directories, or the command line), so it runs on your own computer but not in the sandboxed in-browser engine.

If you want to print full paths of the files in a directory, use the absolute method:

.absolute.say for dir;

🖥 This program reads the local environment (files, directories, or the command line), so it runs on your own computer but not in the sandboxed in-browser engine.

The test named argument of the dir routine allows selecting filenames that match a certain regex, for example, listing all jpeg files:

for dir(test => /\.jpg$/) -> $file {
    say $file.path;
}

🖥 This program reads the local environment (files, directories, or the command line), so it runs on your own computer but not in the sandboxed in-browser engine.

Course navigation

96. The uniq utility   |   98. Text to Morse code