ZetCode

Perl File::Basename and File::Spec

last modified November 25, 2026 Perl 5.44

A path is a string, so it is tempting to take it apart with a regular expression and put it together with a slash. That works until a directory name ends with a slash, a path is just a file name, or the program runs on a system with another separator. Two core modules handle these cases. File::Basename splits a path into a directory, a name and a suffix. File::Spec joins, cleans, splits and converts paths using the rules of the current operating system.

Both modules only work with strings: they do not check whether a path exists. Working with the directories themselves is covered in Perl directories.

basename and dirname

The basename function returns the last component of a path and dirname returns everything in front of it. Both are exported by default.

base_dir.pl
#!/usr/bin/perl

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

my $path = '/home/paul/docs/report.txt';

say basename($path);
say dirname($path);

For an ordinary file path, basename gives the file name and dirname the directory that contains it, without the trailing slash.

$ perl base_dir.pl
report.txt
/home/paul/docs

Edge cases of basename and dirname

The two functions imitate the Unix basename and dirname commands, which matters for paths that end with a slash or have no directory part.

edge_cases.pl
#!/usr/bin/perl

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

my @paths = ('/usr/local/bin/perl', '/usr/local/bin/', 'notes.txt',
    'lib/', '/');

for my $path (@paths) {
    printf "%-22s basename: %-10s dirname: %s\n",
        "'$path'", basename($path), dirname($path);
}

A trailing slash is ignored, so /usr/local/bin/ has the base name bin, and its directory is /usr/local. A path without a slash has the directory ., the current directory, and the root directory is its own base name and directory. This is the reason to use the functions rather than splitting on the last slash by hand: a regex split would return an empty name for lib/ and no directory at all for notes.txt.

$ perl edge_cases.pl
'/usr/local/bin/perl'  basename: perl       dirname: /usr/local/bin
'/usr/local/bin/'      basename: bin        dirname: /usr/local
'notes.txt'            basename: notes.txt  dirname: .
'lib/'                 basename: lib        dirname: .
'/'                    basename: /          dirname: /

Removing suffixes with basename

basename takes an optional list of suffixes after the path. If the name ends with one of them, the suffix is removed.

suffixes.pl
#!/usr/bin/perl

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

my @files = qw(report.txt notes.md archive.tar.gz script.pl);

for my $file (@files) {
    say basename($file, '.txt', '.md', '.tar.gz');
}

The suffixes are plain strings, compared literally. They are tried in order, and each one that the remaining name ends with is removed, so basename($file, '.gz', '.tar') would also turn archive.tar.gz into archive. script.pl matches none of them and is returned unchanged. A multi-part suffix such as .tar.gz is easiest to handle this way, because it is listed explicitly.

$ perl suffixes.pl
report
notes
archive
script.pl

Splitting a path with fileparse

fileparse is the function behind basename and dirname. It returns the name, the directory and the suffix in a single call. Its suffix patterns may be regular expressions.

fileparse.pl
#!/usr/bin/perl

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

my @paths = qw(
    /var/log/nginx/access.log
    backups/site.tar.gz
    /etc/hosts
    data/v1.2/table.csv
);

for my $path (@paths) {
    my ($name, $dir, $suffix) = fileparse($path, qr/\.[^.]*/);
    say "$name | $dir | $suffix";
}

say '';

for my $path (@paths) {
    my ($name, $dir, $suffix) = fileparse($path, qr/\.tar\.gz/, qr/\.[^.]*/);
    say "$name | $dir | $suffix";
}

The pattern qr/\.[^.]*/ matches the last extension. It is anchored at the end of the name, so the dot inside v1.2 is never treated as a suffix, and hosts gets an empty suffix. Unlike dirname, fileparse keeps the trailing slash on the directory, so the three parts concatenate back into the original path.

With the generic pattern alone, site.tar.gz loses only .gz. The patterns are tried in turn, and each one that matches removes its part from the end of the name. The second loop puts qr/\.tar\.gz/ first, so the double extension goes as a whole and the generic pattern finds nothing left to remove.

$ perl fileparse.pl
access | /var/log/nginx/ | .log
site.tar | backups/ | .gz
hosts | /etc/ | 
table | data/v1.2/ | .csv

access | /var/log/nginx/ | .log
site | backups/ | .tar.gz
hosts | /etc/ | 
table | data/v1.2/ | .csv

Joining paths with catfile and catdir

File::Spec is used through class methods. catfile joins directories and a file name, and catdir joins directory names, both with the separator of the current system.

join_paths.pl
#!/usr/bin/perl

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

my $dir = 'data/';
my $file = 'users.csv';

say "concat:   $dir/$file";
say 'catfile:  ', File::Spec->catfile($dir, $file);
say 'catdir:   ', File::Spec->catdir('data', 'archive', '2026');
say 'catfile:  ', File::Spec->catfile('/srv', 'www', 'index.html');

Plain interpolation produces a double slash when the directory already ends with one. catfile cleans the result, so the same code works no matter whether the directory came with a trailing slash or not. An absolute first component, such as /srv, keeps the result absolute.

$ perl join_paths.pl
concat:   data//users.csv
catfile:  data/users.csv
catdir:   data/archive/2026
catfile:  /srv/www/index.html

Cleaning paths with canonpath

The File::Spec::Functions module exports the same operations as plain functions, which reads better when a program calls them often. canonpath returns a cleaned-up version of a path.

canonpath.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Spec::Functions qw(canonpath);

my @paths = ('data//archive/', './notes.txt', 'a/./b/./c',
    '/usr/lib/../bin', '//srv///www/');

for my $path (@paths) {
    printf "%-18s -> %s\n", $path, canonpath($path);
}

canonpath collapses repeated slashes, removes ./ components and the trailing slash. It deliberately leaves .. alone: if /usr/lib were a symbolic link, removing lib/.. would lead to a different directory than the system does. The cleanup is purely textual, so it is safe for paths that do not exist yet.

$ perl canonpath.pl
data//archive/     -> data/archive
./notes.txt        -> notes.txt
a/./b/./c          -> a/b/c
/usr/lib/../bin    -> /usr/lib/../bin
//srv///www/       -> /srv/www

Splitting into directories with splitdir

splitdir breaks a directory path into its components, and catdir reverses the operation. The splitpath and catpath pair splits a path into a volume, a directory and a file instead.

split_dirs.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Spec::Functions qw(splitdir catdir splitpath catpath);

my @parts = splitdir('/home/paul/projects/site');
say scalar @parts, ' parts: ', join ' | ', @parts;

pop @parts;
say 'parent: ', catdir(@parts);

my ($volume, $dirs, $file) = splitpath('/home/paul/notes.txt');
say "volume: '$volume' dirs: '$dirs' file: '$file'";

say catpath($volume, $dirs, 'todo.txt');

The first component of an absolute path is an empty string, which stands for the root; thanks to it, catdir turns the list back into an absolute path. Removing the last element with pop gives the parent directory. splitpath returns an empty volume on Unix; on Windows it would hold the drive letter. catpath puts the three parts together again, here with a different file name.

$ perl split_dirs.pl
5 parts:  | home | paul | projects | site
parent: /home/paul/projects
volume: '' dirs: '/home/paul/' file: 'notes.txt'
/home/paul/todo.txt

Relative and absolute paths

rel2abs turns a relative path into an absolute one, and abs2rel expresses a path relative to a base directory. Without a base, both use the current working directory.

rel_abs.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Spec::Functions qw(rel2abs abs2rel file_name_is_absolute);

my $base = '/srv/www';

say rel2abs('img/logo.png', $base);
say rel2abs('../backup', $base);
say rel2abs('/etc/hosts', $base);

say abs2rel('/srv/www/css/main.css', $base);
say abs2rel('/srv/logs/access.log', $base);

for my $path ('/srv/www', 'srv/www', './www') {
    say "$path absolute: ", file_name_is_absolute($path) ? 'yes' : 'no';
}

The example passes the base directory explicitly, so the results do not depend on where the program is started. An absolute path is returned unchanged by rel2abs. abs2rel climbs out of the base with .. when the target lies elsewhere. Like canonpath, rel2abs does not resolve .., so /srv/www/../backup keeps it. file_name_is_absolute tells the two kinds apart.

$ perl rel_abs.pl
/srv/www/img/logo.png
/srv/www/../backup
/etc/hosts
css/main.css
../logs/access.log
/srv/www absolute: yes
srv/www absolute: no
./www absolute: no

Special directory names

A few functions return the names that the current system uses for special directories. Using them instead of the literal strings keeps the code portable.

special_dirs.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Spec::Functions qw(curdir updir rootdir no_upwards catdir);

say 'curdir:  ', curdir();
say 'updir:   ', updir();
say 'rootdir: ', rootdir();
say 'up two:  ', catdir(updir(), updir(), 'lib');

my @entries = ('.', '..', 'src', 'docs', '.git');
say 'entries: ', join ' ', no_upwards(@entries);

curdir, updir and rootdir return ., .. and / on Unix. no_upwards filters the current and parent directory entries out of a list, which is exactly what a directory listing needs; hidden entries such as .git are kept. File::Spec also provides tmpdir, which returns the directory for temporary files.

$ perl special_dirs.pl
curdir:  .
updir:   ..
rootdir: /
up two:  ../../lib
entries: src docs .git

Handling Windows paths on Unix

Both modules can work with the rules of another system. This is useful when a program reads paths written on Windows, for example from a log file or a configuration file.

windows.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Basename qw(fileparse fileparse_set_fstype);
use File::Spec::Win32;

my $path = 'C:\Users\paul\Documents\notes.txt';

fileparse_set_fstype('MSWin32');
my ($name, $dir, $suffix) = fileparse($path, qr/\.[^.]*/);
say "$name | $dir | $suffix";

my ($volume, $dirs, $file) = File::Spec::Win32->splitpath($path);
say "volume: $volume dirs: $dirs file: $file";

say File::Spec::Win32->catfile('D:', 'backup', 'notes.txt');
say File::Spec::Win32->canonpath('C:/Users//paul/./Desktop');

fileparse_set_fstype switches File::Basename to Windows rules, so the backslash becomes the separator. For File::Spec, the methods are called on the File::Spec::Win32 class instead of File::Spec; the plain File::Spec class is a subclass of the one for the current system. On Windows, splitpath fills the volume slot with the drive letter, and canonpath converts forward slashes to backslashes.

$ perl windows.pl
notes | C:\Users\paul\Documents\ | .txt
volume: C: dirs: \Users\paul\Documents\ file: notes.txt
D:\backup\notes.txt
C:\Users\paul\Desktop

Textual and physical paths

The File::Spec functions never look at the disk. The abs_path function from the core Cwd module does: it resolves .. and symbolic links and returns the real location of an existing path.

physical.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Cwd qw(abs_path);
use File::Spec::Functions qw(canonpath);

for my $path ('/usr/lib/../bin', '/bin', '/usr/missing/../bin') {
    my $real = abs_path($path) // 'undef';
    printf "%-20s canonpath: %-20s abs_path: %s\n",
        $path, canonpath($path), $real;
}

abs_path turns /usr/lib/../bin into /usr/bin, and because /bin is a symbolic link to usr/bin on current Linux distributions, it resolves that too. For a path that does not exist it returns undef. Use canonpath to tidy a path string, and abs_path when the program needs to know where a path really leads.

$ perl physical.pl
/usr/lib/../bin      canonpath: /usr/lib/../bin      abs_path: /usr/bin
/bin                 canonpath: /bin                 abs_path: /usr/bin
/usr/missing/../bin  canonpath: /usr/missing/../bin  abs_path: undef

Mapping a source tree to an output tree

The functions combine well. A static site generator, for example, has to turn each source file into an output file at the same relative location with a different extension.

mirror.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use File::Basename qw(fileparse);
use File::Spec::Functions qw(abs2rel catfile catdir canonpath);

my $src = 'content';
my $out = 'public/';

my @pages = qw(
    content/index.md
    content/blog/2026/first-post.md
    content//about/team.markdown
);

for my $page (@pages) {
    my $rel = abs2rel(canonpath($page), $src);
    my ($name, $dir) = fileparse($rel, qr/\.(?:md|markdown)/);

    my $target = catfile(catdir($out, $dir), "$name.html");
    say "$page -> $target";
}

canonpath first removes the double slash from the third input. abs2rel makes each page relative to the source directory, and fileparse splits the result into a name and a subdirectory while removing either extension. Finally, catdir and catfile build the output path; the trailing slash of public/ and the ./ directory of the top-level page disappear on the way.

$ perl mirror.pl
content/index.md -> public/index.html
content/blog/2026/first-post.md -> public/blog/2026/first-post.html
content//about/team.markdown -> public/about/team.html

Best practices

The following guidelines help when working with paths.

Source

File::Basename · File::Spec · File::Spec::Functions · Cwd

In this article we have split paths with basename, dirname and fileparse, and built, cleaned and converted them with File::Spec. Listing, creating and walking directories is covered in Perl directories, and checking what a path points to in Perl file tests.

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.