Splitting a Filename into Its Component Parts

Problem

You want to extract a filename, its enclosing directory, or the extension(s) from a string that contains a full pathname.

Solution

Use routines from the standard File::Basename module.

use File::Basename;

$base = basename($path);
$dir  = dirname($path);
($base, $dir, $ext) = fileparse($path);

Discussion

The standard File::Basename module contains routines to split up a filename. dirname and basename supply the directory and filename portions respectively:

$path = '/usr/lib/libc.a';
$file = basename($path);    
$dir  = dirname($path);     

print "dir is $dir, file is $file\n";
# dir is /usr/lib, file is libc.a

The fileparse function can be used to extract the extension. To do so, pass fileparse the path to decipher and a regular expression that matches the extension. You must give fileparse this pattern because an extension isn’t necessarily dot-separated. Consider ".tar.gz"--is the extension ".tar", ".gz", or ".tar.gz"? By specifying the pattern, you control which of these you get.

$path = '/usr/lib/libc.a';
($name,$dir,$ext) = fileparse($path,'\..*');

print "dir is $dir, name is $name, extension is $ext\n";
# dir is /usr/lib/, name is libc, extension is .a

By default, these routines parse pathnames using your operating system’s normal conventions for directory separators by looking at the $^O variable, which holds a string identifying the system you’re running on. That value was determined when Perl was built and installed. You can change ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.