By Alvin Alexander. Last updated: June 4, 2016
Question: Using Perl, if I have a string that includes the full path to a file (i.e., it includes both the full path of the directory and the filename), how do I split the string into its directory and filename components?
Answer: Use the basename
and dirname
methods of the Perl File::Basename
module.
The following example shows how to break this string '/Users/al/work/file1.pdf'
into its directory and filename components:
use File::Basename; $fullpath = '/Users/al/work/file1.pdf'; $file = basename($fullpath); $dir = dirname($fullpath); print "file = $file\n"; print "dir = $dir\n";
If you save this Perl code to a file and then run it you'll see this output:
file = file1.pdf dir = /Users/al/work