So, require your module to be one of the first in the list. This worked for me:
runme.pl
#!/usr/bin/perl
# In order to 'use' a perlmodule in a userspace library you need to ad
+d it to @INC.
# But if you do not want to use an absolute path inside the script, yo
+u need this workaround:
BEGIN{
use Cwd 'abs_path';
my $this = $0; # this script
$this =~ s/[^\/]+$//; # strip the filename, now we have a (rel
+ative) directory
my $path = abs_path($this); # now we have an absolute director
+y
unshift @INC, $path; # which we add to @INC
# chdir('/tmp'); # does seem to confuse abs_path! Uncomment to
+ see
}
use My::Module;
My::Module::print_file_name();
My::Module::print_script_name();
My::Module::print_caller_name();
-*Module.pl*- ./My/Module.pm
#!/usr/bin/perl
package My::Module;
use feature qw(say);
local $_SCRIPT = "";
local $_PATH = "";
BEGIN{
use Cwd 'abs_path';
$_PATH = $0; # this script
$_PATH =~ s/([^\/]+)$//; # strip the filename, now we have a (
+relative) directory
$_SCRIPT = $1; # the stripped part is the filename
$_PATH = abs_path($_PATH); # now we have an absolute directory
+
print "My::Module 0=$0 _PATH=$_PATH _SCRIPT=$_SCRIPT \n";
}
sub print_file_name {
say __FILE__;
}
sub print_script_name {
say "print_script_name: $_PATH/$_SCRIPT";
}
sub print_caller_name {
my @D = caller();
$D[1]= abs_path($_PATH.'/'.$D[1]) unless $D[1]=~m{^/};
say "print_caller_name: @D";
}
1;
If you bet on the fact that if chdir() was done, and that new directory does NOT contain the script that was run, You can add a kill or warning in the BEGIN block of the Module.pm, like:
warn "ALERT ALERT ALERT" unless(-f "$_PATH/$_SCRIPT");