Relative file paths in perl

I have a perl script that uses relative file paths.

Relative paths apparently refer to the location from which the script is being run, and not to the location of the perl script. How to make my relative paths relative to the location of the script?

For example, I have a directory structure

dataFileToRead.txt ->bin myPerlScript.pl ->output 

inside perl script I open the file dataFileToRead.txt using the code my $ rawDataName = "../dataFileToRead.txt"; open INPUT, "<", $ rawDataName;

If I run perl script from bin directory, it works fine

If I run it from the parent directory, it will not be able to open the data file.

+6
source share
4 answers

FindBin is the classic solution to your problem. If you write

 use FindBin; 

then the $FindBin::Bin scalar is the absolute path to the location of your Perl script. You can chdir there before you open the data file, or simply use it in the path of the file you want to open

 my $rawDataName = "$FindBin::Bin/../dataFileToRead.txt"; open my $in, "<", $rawDataName; 

(By the way, it is always better to use lexical file descriptors on nothing but the very old perl.)

+13
source

To include a relative path in an absolute, you can use Cwd :

 use Cwd qw(realpath); print "'$0' is '", realpath($0), "'\n"; 
+3
source

Start by figuring out where the script is .

Then get the directory in which it is located. You can use Path :: Class :: File dir() for this.

Finally, you can use chdir to change the current working directory to the directory just identified.

So, theoretically:

 chdir(Path::Class::File->new(abs_path($0))->dir()); 
+1
source

Source: https://habr.com/ru/post/909735/


All Articles