How can I get the absolute path of my Perl program from its relative path?

这一生的挚爱 提交于 2019-12-12 14:25:47

问题


I need to find the full path to the Perl script I'm currently running, i.e.

  • for ~/dir/my.pl I would need it to be "/home/user/dir/my.pl". The $0 will give me "~/dir/my.pl".

  • for ./my.pl I would still need "/home/user/dir/my.pl"

etc. Thanks!


回答1:


Use the FindBin module:

$ cat /tmp/foo/bar/baz/quux/prog
#! /usr/bin/perl

use FindBin;

print "$FindBin::Bin/$FindBin::Script\n";

$ PATH=/tmp/foo/bar/baz/quux prog
/tmp/foo/bar/baz/quux/prog

$ cd /tmp/foo/bar/baz/quux

$ ./prog 
/tmp/foo/bar/baz/quux/prog



回答2:


It sounds like you're looking for the rel2abs function in File::Spec. For example:

#!/usr/bin/perl

use File::Spec;
my $location = File::Spec->rel2abs($0);
print "$location\n";

This will resolve $0 in the way you describe:

$ ./myfile.pl
/Users/myname/myfile.pl
$ ~/myfile.pl
/Users/myname/myfile.pl

Alternatively, you could use Cwd::abs_path in the exact same way.




回答3:


You should take a look at FindBin or FindBin::Real.




回答4:


Looks like you just need to expand the paths to their absolute values. Check this article for how to do that.




回答5:


Use FindBin Module




回答6:


Many of the concepts mentioned will break in case that the file itself is a symbolic link. I usually start my scripts in the following way:

use strict;
use English;
use warnings;

use Cwd qw(realpath);
use File::Basename;
use lib &File::Basename::dirname(&Cwd::realpath($PROGRAM_NAME));

Hopefully this helps.



来源:https://stackoverflow.com/questions/1033474/how-can-i-get-the-absolute-path-of-my-perl-program-from-its-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!