1. Perl
  2. Module
  3. here

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

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

  • basename -Get the base name of the file
  • dirname - Get directory name
  • fileparse - A little more detailed operation

To use these functions, it's a good idea to import them explicitly.

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

basename function

Use the basename function to get the base name of a file. The base name is the last part of the file name.

# Get base name
$basename = basename $file;

dirname function

Use the dirname function to get the directory name.

# Get directory name
$dirname = dirname $file;

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

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

A little more detailed operation on the file name

You can use fileparse to get the base name and directory name at once.

# Get base name and directory name
($basename, $dirname) = fileparse $file;

Also, if you specify the extension with regular expression in the second argument of fileparse, you can retrieve the extension and the base name separately.

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

This is an example to extract the extension. Specify a regular expression as the second argument. The regular expression "\ .. * $" means ". Comes and ends with 0 or more characters that can be anything." If $file is "dir/a.txt", $basename will be "a" and $ext will be ".txt".

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

The above is an example of extracting the extension, but if two extensions continue, the extension after the first extension will be extracted. For example, if the file name is "dir/a.txt.gz", $ext will be ".txt.gz".

If you want to retrieve ".gz", change the regular expression to "\. [^\.] * $". The meaning of this regular expression is that ". Comes and ends with 0 or more characters other than.".

Related Informatrion