Perl Newbies

  1. Perl
  2. Modules
  3. here

File::Basename - Get the base name of a file

File::Basename is a module to get the base name a file and the directory name of a file. You can use the following three functions.

  • basename - Get the base name of a file
  • dirname - Get the directory name of a file
  • fileparse - A little more complex operations

It is good to import these functions explicitly.

# Import functions
use File::Basename 'basename', 'dirname';

basename function

basename function gets the base name of the file. the base name means the last part of the file name (If a file is "/foo/bar/baz.txt", the base name is "baz.txt").

# Get the base name of a file
$basename = basename $file;

dirname function

dirname gets the directory name of a file.

# Get directory name
$dirname = dirname $file;

Examples of basename function and dirname function. If a file is "dir/a.txt", you can get "a.txt" as the base name and get "dir" as the directory name.

# Get the base name and the directory name of a file
use File::Basename qw/basename dirname/;
my $file = 'dir/a.txt';
my $basename = basename $file;
my $dirname = dirname $file;

A little more complex operations of a file

If you use fileparse function, you can get the base name and directory name of a file at once.

# Get the base name and directory name of a file at once
($basename, $dirname) = fileparse $file;

If you pass a extension usingregular expression to the second argument of fileparse, you can get the base name and extension separately.

# Get base name, directory name, extension
($basename, $dirname, $ext) = fileparse($file, $regex);

Example of extracting the extension using a regular expression. The regular expression "\..*$" means ". come, zero or more any characters come, end of the string come". If $file is "dir/a.txt", $basename becomes "a" and $ext becomes ".txt".

# Extract the extension
use File::Basename 'fileparse';
my $file = 'dir/a.txt';
my ($basename, $dirname, $ext) = fileparse($file, qr/\..*$/);

The above example extracts the extension, but if the extension continues twice, the extension after the first extension is extracted. For example, if the file name is "dir/a.txt.gz", $ext becomes ".txt.gz".

If you want to extract ".gz", change the regular expression to "\.[^\.]*$". This regular expression means ". come, zero or more characters except . come, ,end of the string come".

Menu