Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How to determine absolute path of current Perl file?

by FreeBeerReekingMonk (Deacon)
on Feb 29, 2016 at 21:48 UTC ( [id://1156483]=note: print w/replies, xml ) Need Help??


in reply to How to determine absolute path of current Perl file?

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");

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1156483]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-03-28 17:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found