9.10. Splitting a Filename into Its Component PartsProblemYou want to extract a filename, its enclosing directory, or the extension(s) from a string that contains a full pathname. SolutionUse 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. $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 $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
fileparse_set_fstype("MacOS");
$path = "Hard%20Drive:System%20Folder:README.txt";
($name,$dir,$ext) = fileparse($path,'\..*');
print "dir is $dir, name is $name, extension is $ext\n";
# dir is Hard%20Drive:System%20Folder, name is README, extension is .txt
To pull out just the extension, you might use this:
sub extension {
my $path = shift;
my $ext = (fileparse($path,'\..*'))[2];
$ext =~ s/^\.//;
return $ext;
}
When called on a file like
source.c.bak
, this returns an extension of
When passed a pathname with a trailing directory separator, such as See Also
The documentation for the standard File::Basename module (also in
Chapter 7
of
Programming Perl
); the entry for |
|