What is the basename() method in Perl?

Overview

The basename() method in Perl is used to return the name of a file. It can also take the extension name of the file. The file name is returned without its extension.

Syntax

basename(file_path, [suffix])

Parameters

file_path: This is the name or the file path of the file we want to get its base name.

suffix: This is an optional argument. It is the extension of the file we want to get its base name.

Return value

This method returns the file name of the file. If the suffix argument is supplied, then the file name will be returned without its extension.

Example

Let’s look at the code below:

# import routine
use File::Basename;
# get base names
$file1 = basename("main.perl");
$file2 = basename("app.js");
$file3 = basename("coding/main.perl");
$file4 = basename("coding/app.js", ".js");
# print base names
print "$file1\n";
print "$file2\n";
print "$file3\n";
print $file4;

Explanation

  • Line 2: We import the File::Basename routing. It helps us parse file paths into their directory, filename, and suffix.

  • Lines 5 to 8: We create the file paths we need. We get the base names using the basename() function.

  • Lines 11 to 14: We print the basenames of the files.

Free Resources