I have a bunch of perl codes in a hierarchy somewhat like this:
Where data.txt is an ascii file and the contents of demo1.pl, demo2.pl & mylib.pm are list below:
This package is intended to be installed in anywhere on any hosts in house. Therefore, there is no way to know the absolute path of ‘data.txt’.
However, both demo1.pl and demo2.pl are expected to be run from the current directory, i.e. ‘.’. So my problem is how to correctly define the relative path for ‘data.txt’ in mylib.pm? As the current implementation shown in mylib.pm, demo1.pl is run ok.
But demo2.pl can not find ‘data.txt’, unless I commented out the blue line and uncommented the red line:
I guess that I must have missed something that’s very basic.
Please help. Many thanks.
Code:
[b]% ls *[/b]
demo1.pl*
subdir1:
demo2.pl* mylib.pm
subdir2:
data.txt
Code:
[b]% cat demo1.pl[/b]
#! /usr/bin/perl
use lib "./subdir1";
use mylib;
print "This is $0...\n";
# More implementations here
[b]% cat ./subdir1/demo2.pl[/b]
#! /usr/bin/perl
use mylib;
print "This is $0...\n";
# More implementations here
[b]% cat ./subdir1/mylib.pm[/b]
package mylib;
[COLOR=blue]my $datafile = './subdir2/data.txt'; # To satisfy demo1.pl[/color]
[COLOR=red][b]#my $datafile = '../subdir2/data.txt'; # To satisfy demo2.pl[/b][/color]
if(-e $datafile) {
print "File '$datafile' is found.\n";
}
else {
print "File '$datafile' is NOT found.\n";
}
# some implementation here
1;
However, both demo1.pl and demo2.pl are expected to be run from the current directory, i.e. ‘.’. So my problem is how to correctly define the relative path for ‘data.txt’ in mylib.pm? As the current implementation shown in mylib.pm, demo1.pl is run ok.
Code:
[b]% ./demo1.pl[/b]
File './subdir2/data.txt' is found.
This is ./demo1.pl...
Code:
[b]% ./demo2.pl[/b]
[b]File './subdir2/data.txt' is NOT found.[/b]
This is ./demo2.pl...
Please help. Many thanks.