Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative file paths in perl

I have a perl script which is using relative file paths.

The relative paths seem to be relative to the location that the script is executed from rather than the location of the perl script. How do I make my relative paths relative to the location of the script?

For instance I have a directory structure

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

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

If I run the perl script from the bin directory then it works fine

If I run it from the parent directory then it can't open the data file.

like image 769
Dunc Avatar asked Mar 01 '12 12:03

Dunc


3 Answers

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

use FindBin;

then the scalar $FindBin::Bin is the absolute path to the location of your Perl script. You can chdir there before you open the data file, or just use it in the path to 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 handles on anything but a very old perl.)

like image 63
Borodin Avatar answered Sep 23 '22 13:09

Borodin


To turn a relative path into an absolute one you can use Cwd :

use Cwd qw(realpath);
print "'$0' is '", realpath($0), "'\n";
like image 39
JRFerguson Avatar answered Sep 20 '22 13:09

JRFerguson


Start by finding out where the script is.

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

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

So, in theory:

chdir(Path::Class::File->new(abs_path($0))->dir());
like image 20
Quentin Avatar answered Sep 23 '22 13:09

Quentin