Reputation: 8078
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.
Upvotes: 8
Views: 22053
Reputation: 7526
To turn a relative path into an absolute one you can use Cwd :
use Cwd qw(realpath);
print "'$0' is '", realpath($0), "'\n";
Upvotes: 3
Reputation: 126772
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.)
Upvotes: 15
Reputation: 944527
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());
Upvotes: 1
Reputation: 213200
Relative paths are relative to the current working directory. If you don't have any control over the working directory then you need to find a more robust way to spcecify your file paths, e.g. use absolute paths, or perhaps relative paths which are relative to some specific location within the file system.
Upvotes: 0