Multiple ways to get executable script file name and path in Perl with an example

This tutorial explains how to get the name of the file and the full path of a Perl script execution file.

How to get the file name and full path to a Perl script that is executing?

There are multiple ways to get the following things

  • Name of the Perl script file

  • Full path of the Perl script file

  • use the Cwd module

The Cwd module provides the abs_path function that gets the absolute path of a file

  • import abs_path function using use in code

    .

  • First, get the name of the file using the Perl special variable $0, It returns the name of the file - HelloWorld.pl

  • call the abs_path function with the file name and returns the absolute path of a file

use Cwd 'abs_path';
print ($0,"\n");# HelloWorld.pl
print abs_path($0);# c:/perlwork/Helloworld.pl

Second-way using the File::Spec module that contains rel2abs function Perl script stores information in __FILE__. pass this to the rel2abs function

use File::Spec;
my $file=File::Spec->rel2abs( __FILE__ );
print ($file,"\n");# c:/perlwork/Helloworld.pl

The third way, using the FindBin🔗 module that gets the full directory of the Perl script. The $Bin variable from FindBin returns the full folder path of a Perl script file.

use FindBin '$Bin';
print "$Bin.\n";# c:/perlwork/Helloworld.pl

Conclusion

Learned multiple ways to get the name of a Perl script file and full absolute path in Perl with code examples.