ZetCode

Perl directories

last modified November 25, 2026 Perl 5.44

Perl works with directories through a small set of built-in functions and two core modules. opendir, readdir and closedir list a directory, glob finds paths that match a wildcard pattern, and mkdir, rmdir and chdir create, remove and enter directories. File::Path creates and removes whole trees, and File::Find walks them recursively.

The examples work with the following sample directory. It contains a hidden file, a hidden .git directory, an empty directory and a directory with a space in its name.

$ tree -an project
project
├── data
├── docs
│   ├── api.md
│   └── guide.md
├── .git
│   ├── HEAD
│   └── hooks
│       └── check.pl
├── .gitignore
├── notes.txt
├── old notes
│   └── 2025.txt
├── README.md
├── src
│   ├── app.pl
│   ├── lib
│   │   └── Helper.pm
│   └── Util.pm
└── todo.txt

7 directories, 12 files

Listing a directory

A directory is read through a directory handle. opendir opens the handle, readdir returns one entry at a time, and closedir releases the handle.

list_dir.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

opendir my $dh, 'project' or die "Cannot open project: $!";

while (my $name = readdir $dh) {
    say $name;
}

closedir $dh;

In scalar context, readdir returns the next entry name, and undef when there are no more entries, which ends the loop. Like open, opendir returns false on failure and sets $!.

The output shows two things to keep in mind. The list includes the special entries . and .., the directory itself and its parent. And the entries come in the order in which the file system stores them, which is not alphabetical and may differ between machines.

$ perl list_dir.pl
.
README.md
docs
.gitignore
notes.txt
data
todo.txt
.git
src
old notes
..

Filtering and sorting entries

In list context, readdir returns all remaining entries at once. The list is then filtered with grep and put in a predictable order with sort.

sorted.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

opendir my $dh, 'project' or die "Cannot open project: $!";
my @entries = readdir $dh;
closedir $dh;

my @names  = sort grep { $_ ne '.' && $_ ne '..' } @entries;
my @hidden = grep { /^\./ } @names;
my @visible = grep { !/^\./ } @names;

say "all:     @names";
say "hidden:  @hidden";
say "visible: @visible";

The first grep removes only . and .., so hidden entries such as .gitignore stay in the list. Testing for a leading dot then separates the hidden entries from the visible ones. The default sort compares strings by code point, so uppercase names such as README.md come before lowercase ones.

$ perl sorted.pl
all:     .git .gitignore README.md data docs notes.txt old notes src todo.txt
hidden:  .git .gitignore
visible: README.md data docs notes.txt old notes src todo.txt

Building full paths

readdir returns bare names, without the directory part. Before a name can be tested or opened, it has to be joined with the directory it came from.

full_paths.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $dir = 'project';

opendir my $dh, $dir or die "Cannot open $dir: $!";
my @names = sort grep { !/^\./ } readdir $dh;
closedir $dh;

say 'wrong: ', join ' ', grep { -d } @names;

for my $name (@names) {
    my $path = "$dir/$name";
    say -d $path ? "$path/" : $path;
}

The first line applies the -d directory test to the bare names. They are looked up relative to the current working directory, not to project, so no directory is found. The loop builds the full path first, and -d then works as expected; directories are printed with a trailing slash. The file test operators are covered in Perl file tests, and joining paths portably in Perl File::Basename and File::Spec.

$ perl full_paths.pl
wrong: 
project/README.md
project/data/
project/docs/
project/notes.txt
project/old notes/
project/src/
project/todo.txt

Finding files with glob

The glob function expands shell wildcards and returns the matching paths. Unlike readdir, it returns paths with the directory part included.

glob_files.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @text = glob 'project/*.txt';
say "text:    ", join ", ", @text;

my @all = glob 'project/*';
say "all:     ", join ", ", @all;

my @code = glob 'project/src/*.{pl,pm}';
say "code:    ", join ", ", @code;

my @nested = glob 'project/*/*.md';
say "nested:  ", join ", ", @nested;

my @dotfiles = glob 'project/.*';
say "dot:     ", join ", ", @dotfiles;

* matches any sequence of characters, and braces list alternatives, so *.{pl,pm} finds both scripts and modules. The wildcard can appear in a directory component too: project/*/*.md looks one level down. The results are sorted alphabetically without regard to case, so README.md appears between old notes and src.

As in the shell, * does not match names that start with a dot. Hidden entries need an explicit .* pattern, which also matches . and ...

$ perl glob_files.pl
text:    project/notes.txt, project/todo.txt
all:     project/data, project/docs, project/notes.txt, project/old notes, project/README.md, project/src, project/todo.txt
code:    project/src/app.pl, project/src/Util.pm
nested:  project/docs/api.md, project/docs/guide.md
dot:     project/., project/.., project/.git, project/.gitignore

glob and spaces in paths

glob splits its argument on whitespace and treats each part as a separate pattern. A directory name with a space therefore breaks the pattern. bsd_glob from the core File::Glob module treats the whole argument as one pattern.

glob_spaces.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Glob qw(bsd_glob);

my $dir = 'project/old notes';

my @wrong = glob "$dir/*.txt";
say "glob:     ", join ", ", @wrong;

my @right = bsd_glob("$dir/*.txt");
say "bsd_glob: ", join ", ", @right;

glob sees two patterns, project/old and notes/*.txt. The second matches nothing. The first contains no wildcard, so it is returned as it is, even though no such path exists. bsd_glob finds the file. Use it whenever the pattern contains a variable that may hold a space.

$ perl glob_spaces.pl
glob:     project/old
bsd_glob: project/old notes/2025.txt

Creating directories with mkdir

The mkdir function creates one directory. It returns true on success; on failure it returns false and sets $!.

make_dir.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

mkdir 'logs' or die "Cannot create logs: $!";
say 'logs created';

if (mkdir 'logs') {
    say 'created again';
} else {
    say "second mkdir: $!";
}

mkdir 'reports/2026/q1' or say "nested mkdir: $!";

say 'logs is a directory' if -d 'logs';

The first call creates logs. The second fails, because the directory already exists, and the program reports the reason instead of dying. mkdir also fails for reports/2026/q1: it creates only the last component, and the parent directories do not exist. An optional second argument sets the permissions, for example mkdir 'logs', 0700; the process umask is applied to it.

$ perl make_dir.pl
logs created
second mkdir: File exists
nested mkdir: No such file or directory
logs is a directory

Creating directory trees with make_path

The make_path function from the core File::Path module creates a directory together with any missing parents, like mkdir -p in the shell.

make_path.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Path qw(make_path);

my @created = make_path('reports/2026/q1', 'reports/2026/q2');
say "created: $_" for @created;

my @again = make_path('reports/2026/q1');
say 'second call created ', scalar @again, ' directories';

make_path('project/README.md/sub', { error => \my $err });

for my $diag (@$err) {
    my ($path, $msg) = %$diag;
    say "failed: $path: $msg";
}

make_path accepts several paths and returns the directories it actually created, parents included. Existing directories are not an error, so the second call simply creates nothing. By default, failures are reported as warnings; with the error option they are collected in an array of single-entry hashes that map the path to the message. Here the path runs through a regular file, so both the file and the subdirectory below it are reported.

$ perl make_path.pl
created: reports
created: reports/2026
created: reports/2026/q1
created: reports/2026/q2
second call created 0 directories
failed: project/README.md: File exists
failed: project/README.md/sub: Not a directory

Removing directories

rmdir removes a directory only when it is empty. remove_tree from File::Path deletes a directory with everything in it.

remove_dir.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Path qw(make_path remove_tree);

mkdir 'backup' or die "Cannot create backup: $!";
rmdir 'backup' or die "Cannot remove backup: $!";
say 'empty backup removed';

rmdir 'project' or say "rmdir project: $!";

make_path('backup/2026/daily');
open my $fh, '>', 'backup/2026/daily/db.sql' or die $!;
close $fh;

my $count = remove_tree('backup');
say "remove_tree deleted $count entries";
say 'backup is gone' unless -e 'backup';

The empty backup directory is removed with rmdir. The same call on project fails because the directory still has entries, which makes rmdir safe to use in cleanup code. The remove_tree function has no such safety net. It returns the number of deleted files and directories, here three directories and one file, so it should only be given paths that the program itself created.

$ perl remove_dir.pl
empty backup removed
rmdir project: Directory not empty
remove_tree deleted 4 entries
backup is gone

Walking a tree with File::Find

The find function from the core File::Find module visits every file and directory below a starting point. For each entry it calls a subroutine given as the wanted option.

find_all.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Find;

sub show {
    say $File::Find::name;
}

find({
    wanted     => \&show,
    preprocess => sub { sort @_ },
    no_chdir   => 1,
}, 'project');

Inside the callback, $File::Find::name holds the full path of the current entry. By default find changes into each directory it visits; no_chdir keeps the working directory unchanged. The preprocess option receives the entries of each directory and returns the list to visit, here sorted, so the output is the same on every machine. Within a directory, the files come before the subdirectories, because find descends into a subdirectory only after it has handled the entries next to it.

$ perl find_all.pl
project
project/.gitignore
project/README.md
project/notes.txt
project/todo.txt
project/.git
project/.git/HEAD
project/.git/hooks
project/.git/hooks/check.pl
project/data
project/docs
project/docs/api.md
project/docs/guide.md
project/old notes
project/old notes/2025.txt
project/src
project/src/Util.pm
project/src/app.pl
project/src/lib
project/src/lib/Helper.pm

Filtering and pruning with File::Find

A wanted subroutine usually collects only some entries. Setting $File::Find::prune tells find not to descend into the current directory at all.

find_code.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Find;

my @modules;

sub wanted {
    if (-d && /^\./ && $_ ne '.') {
        $File::Find::prune = 1;
        return;
    }

    push @modules, $File::Find::name if -f && /\.p[lm]$/;
}

find(\&wanted, 'project');

say for sort @modules;

Without no_chdir, find runs the callback inside the directory being visited, and $_ holds the bare name of the entry. The file tests therefore work on $_ directly. Hidden directories are pruned, so the hook script in .git/hooks is not collected; the starting directory appears as . and is excluded from the test. The callback visits entries in file system order, so the results are sorted at the end.

$ perl find_code.pl
project/src/Util.pm
project/src/app.pl
project/src/lib/Helper.pm

Directory sizes

The callback can accumulate results as well. The following program adds up the file sizes of each top-level directory, like a minimal du.

dir_sizes.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Find;

my %size;

sub add_size {
    return unless -f;

    my ($top) = $File::Find::name =~ m{^project/([^/]+)/};
    $top //= '(top level)';

    $size{$top} += -s _;
}

find({ wanted => \&add_size, no_chdir => 1 }, 'project');

for my $dir (sort { $size{$b} <=> $size{$a} or $a cmp $b } keys %size) {
    printf "%-12s %5d bytes\n", $dir, $size{$dir};
}

A regular expression extracts the first directory below project from each file path; files directly in project do not match and are counted as the top level. The -f test fetches the file's metadata, and -s _ reuses it to get the size without another system call. The hash is printed from the largest total to the smallest, with names as a tie-breaker.

$ perl dir_sizes.pl
src             83 bytes
(top level)     58 bytes
docs            55 bytes
.git            29 bytes
old notes       12 bytes

Changing the working directory

chdir changes the current working directory of the process, and getcwd from the core Cwd module returns it. Relative paths are resolved against the working directory.

work_dir.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Cwd qw(getcwd);

sub here {
    my ($last) = getcwd() =~ m{([^/]+)$};
    return $last;
}

say 'start:   ', here();

chdir 'project/src' or die "Cannot chdir: $!";
say 'now in:  ', here();

opendir my $dh, '.' or die $!;
say 'entries: ', join ' ', sort grep { !/^\./ } readdir $dh;
closedir $dh;

chdir '../..' or die "Cannot chdir: $!";
say 'back in: ', here();

The here function prints only the last component of the absolute path returned by getcwd. After the first chdir, the directory name . refers to project/src, so opendir lists its entries. The second chdir goes back two levels. The working directory belongs to the whole process, so a program that changes it should change it back, or better, work with full paths instead.

$ perl work_dir.pl
start:   work
now in:  src
entries: Util.pm app.pl lib
back in: work

Best practices

The following guidelines help when working with directories.

Source

perlfunc: opendir · perlfunc: readdir · perlfunc: glob · File::Glob · File::Path · File::Find · Cwd

In this article we have listed directories with readdir and glob, created and removed them with mkdir, rmdir and File::Path, and walked directory trees with File::Find. Splitting and joining paths is covered in Perl File::Basename and File::Spec, and an object-oriented alternative for both in Perl Path::Tiny.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.