📘 Reading directory content using Perl 6

📘 Reading directory content using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Print the file names from the current directory.

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

say dir();

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;

The code is equivalent to the more verbose fragment:

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

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

.absolute.say for dir;

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;

Leave a Reply

Your email address will not be published. Required fields are marked *