Saturday, July 9, 2011

How to Parse File Paths in Perl Using File::Basename

Using the File::Basename Module in Perl

The File::Basename module provides a simple way to parse file paths into their core components: the directory, the file's base name, and the file extension.

Code Example:

use File::Basename;

# Extract all components at once
my ($name, $path, $suffix) = fileparse($fullname, @suffixlist);

# Extract just the filename (with or without a specific suffix)
my $name = fileparse($fullname, @suffixlist);

# Get just the base filename (equivalent to the Unix 'basename' command)
my $basename = basename($fullname, @suffixlist);

# Get just the directory path (equivalent to the Unix 'dirname' command)
my $dirname = dirname($fullname);

No comments: