Lesson 23 of 43 ยท Files and I/O
Directories and File Tests
Check files with -e -f -d -s, list folders with opendir and glob, walk trees with File::Find, and handle paths portably with File::Spec, File::Basename and Path::Tiny.
Real programs rarely deal with just one file. They look for log files in a folder, skip anything that is not a regular file, create output directories, and build paths that work on Windows and Linux alike. Perl has built-in file test operators for questions about a file, functions for reading directories, and a set of core modules that cover walking trees, splitting paths and copying files.
This lesson tours all of them, and ends with Path::Tiny, a popular module from CPAN that wraps many of these tasks in one friendly interface. You will use them together with the file handling from Reading and Writing Files.
Perl is not installed on this site, so the Perl code is read-only. The interactive examples are Bash stand-ins that build a small folder in a temporary location and do the same jobs: test files, list a directory and walk a tree.
File test operators
A file test is a dash followed by one letter, applied to a file name or an open filehandle. It returns true or false (and sometimes a useful value):
| Test | Question |
|---|---|
-e |
Does it exist? |
-f |
Is it a plain file? |
-d |
Is it a directory? |
-l |
Is it a symbolic link? |
-r -w -x |
Can I read, write, execute it? |
-s |
Is it non-empty? (returns the size in bytes) |
-z |
Is it empty? |
-M |
How old is it? (days since last modification, measured from when the script started) |
use v5.36;
for my $path ("notes.txt", "photos", "missing.txt") {
if (-f $path) { say "$path is a file, ", -s $path, " bytes" }
elsif (-d $path) { say "$path is a directory" }
else { say "$path does not exist" }
}
For a 12-byte notes.txt, an existing photos folder and no missing.txt, the output is:
notes.txt is a file, 12 bytes photos is a directory missing.txt does not exist
Tests can be stacked (Perl 5.10 and later), reading right to left: -f -r -w $file asks whether it is a plain file and readable and writable. When you leave the name out, a test uses $_, which makes tests handy inside grep:
my @files = grep { -f } glob("*");
For everything about a file at once, call stat($file), which returns a list that includes the size (element 7) and modification time (element 9). The core File::stat module wraps that list in an object with readable methods such as ->size and ->mtime.
A file test followed by an action is a race: the file may change between the two steps. For reading, writing and creating, just try the operation and check the result, as shown in Reading and Writing Files. Use tests for decisions, such as which files to process.
Listing a directory
Open a directory with opendir, read its names with readdir, and close it with closedir:
my $dir = "photos";
opendir(my $dh, $dir) or die "Cannot open '$dir': $!";
my @names = sort grep { !/^\./ } readdir($dh);
closedir($dh);
say for @names;
Three details matter here:
readdirreturns names only, not paths. To test a file, prepend the folder:-f "$dir/$name". A common bug is testing the bare name, which looks in the current directory instead.- The list includes
.and.., and any hidden files. Thegrep { !/^\./ }removes everything that starts with a dot. - The order is not defined, so
sortif you want a stable result.
For simple patterns, glob is shorter. It expands shell-style wildcards and returns matching paths, sorted alphabetically:
my @text = glob("photos/*.txt");
my @docs = glob("docs/*.{md,txt}"); # braces give alternatives
One catch: glob splits its argument on spaces, so a path such as "My Photos/*.jpg" is read as two patterns. For paths with spaces, load File::Glob ':bsd_glob', which treats spaces literally.
Three ways to find files
Always join the folder and the name before testing a path.
Path helpers
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Walking a tree with File::Find
opendir looks at one folder. To visit every file in a folder and all its subfolders, use the core module File::Find. You give it a callback, and it calls the function for each entry:
use File::Find;
my @logs;
find(sub {
return unless -f $_;
return unless /\.log$/;
push @logs, $File::Find::name;
}, "logs");
say for sort @logs;
Inside the callback, three variables describe the current entry:
$_is the base name of the entry (for exampleapp.log).$File::Find::nameis its full path (for examplelogs/2026/app.log).$File::Find::diris the folder it is in.
By default, File::Find changes the working directory into each folder while it walks, so file tests on $_ work. If you would rather keep the current directory and get full paths in $_, pass options with no_chdir:
find({ wanted => sub { say $_ if -f $_ }, no_chdir => 1 }, "logs");
The visiting order is unspecified, so collect results and sort them when the order matters. For huge trees, the same callback style avoids loading every name into memory first.
Paths and folders with core modules
Core modules handle the details that trip people up when paths are built by hand.
File::Spec builds paths with the right separator for the operating system (/ on Linux and macOS, a backslash on Windows):
use File::Spec;
my $path = File::Spec->catfile("reports", "2026", "summary.txt");
say $path; # reports/2026/summary.txt (on Linux)
File::Basename splits paths into parts. fileparse returns the name, the folder (with its trailing slash) and a suffix that matches your pattern:
use File::Basename;
say basename("/data/logs/app.log"); # app.log
say dirname("/data/logs/app.log"); # /data/logs
my ($name, $folder, $ext) = fileparse("/data/logs/app.log", qr/\.[^.]*/);
say "$name | $folder | $ext"; # app | /data/logs/ | .log
File::Path creates and removes whole trees, like mkdir -p and rm -r. The plain built-in mkdir fails if the parent does not exist:
use File::Path qw(make_path remove_tree);
make_path("out/2026/august"); # creates every missing level
remove_tree("out"); # deletes the folder and everything inside
remove_tree deletes recursively and does not ask. Print the path first, never build it from unchecked input, and avoid running it on a variable that could be empty.
Other helpers worth knowing: File::Copy (copy, move), File::Temp (safe temporary files and folders), and Cwd (getcwd returns the current directory). The built-ins unlink (delete files), rename, mkdir and rmdir (remove an empty folder) cover the basics.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Path::Tiny
The modules above are part of Perl itself. Many modern programs also use Path::Tiny from CPAN (see CPAN and Dependency Management for installing modules). It has no dependencies beyond core Perl, and it wraps path building, folder creation, listing and reading and writing files in one object:
use v5.36;
use Path::Tiny;
my $dir = path("reports");
$dir->mkpath; # make_path in one call
my $file = $dir->child("summary.txt");
$file->spew_utf8("Total: 42\n"); # write the whole file
say $file->slurp_utf8; # read it back
for my $f ($dir->children(qr/\.txt$/)) {
say $f->basename; # summary.txt
}
child builds paths without manual separators, spew_utf8 and slurp_utf8 open, encode, write or read and close in one step, and children lists a folder, optionally filtered by a pattern. The object also has ->exists, ->is_dir, ->lines_utf8({ chomp => 1 }), ->remove_tree and an ->iterator({ recurse => 1 }) for walking trees. For quick scripts, it removes most of the boilerplate you saw earlier in this lesson.
Check your understanding
Quick check ยท 5 questions
of 5 answered You scored / 5 ยท perfect!
-
1. What does
-s $filereturn for a non-empty file?-sis false for an empty file and returns the size in bytes (a true value) otherwise, so it works both as a test and as a size query. -
2. Why does
grep { -f } readdir($dh)often misbehave?readdirgives bare names such asa.txt. Unless the current directory is the one you read, you must test"$dir/$name". -
3. In a
File::Findcallback, which variable holds the full path of the current entry?$File::Find::nameis the full path.$_is the base name (unlessno_chdiris set), and$File::Find::diris the containing folder. -
4. Which module call builds a path with the correct separator for the current operating system?
File::Spec->catfilejoins the parts of a path using the separator of the platform the program runs on. -
5. What is
remove_tree("out")the equivalent of?remove_treefromFile::Pathdeletes a folder and everything inside it, so use it carefully.
Summary
- File tests such as
-e,-f,-d,-s,-zand-Manswer questions about a path; they can be stacked and default to$_. opendir/readdirreturns names only, including.and.., in no defined order;globgives sorted matching paths.File::Findvisits a whole tree through a callback; use$File::Find::namefor the full path andsortthe results.File::Spec,File::BasenameandFile::Pathbuild, split and create paths portably;remove_treedeletes recursively.Path::Tinyfrom CPAN wraps these tasks in one convenient object.- Prefer trying an operation and handling failure over testing first.
Next, put file reading and default variables to work in Text Processing Idioms.
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of Perl lessons completed