πŸ“˜ Reading directory content using Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s