Search⌘ K
AI Features

Directories and Paths

Explore how to efficiently manage directories and file paths in Perl, including opening and reading directories, handling relative and absolute paths, and using modules like File::Spec and Path::Class for portable filesystem manipulation.

Manipulating directories

Working with directories is similar to working with files, except that we can’t write to directories.

Open a directory

Open a directory handle with the opendir built-in:

opendir my $dirh, '/home/monkeytamer/tasks/';

Read from a directory

The readdir built-in reads from a directory. As with readline, you may iterate over the contents of directories one entry at a time or you may assign everything to an array in one swoop:

Perl
# iteration
while (my $file = readdir $dirh) {
...
}
# flatten into a list, assign to array
my @files = readdir $otherdirh;

In a while loop, readdir sets $_: ...