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

I need to find the full path to the Perl script that I am currently executing, i.e.

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

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

etc .. thanks!

+3
source share
6 answers

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
+6
source

It looks like you are looking for the relaabs function in the :: Spec file . For example:

#!/usr/bin/perl

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

This will solve $ 0 in the way you describe:

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

Cwd:: abs_path .

+5
+2

, . , .

+1

FindBin

0

, . :

use strict;
use English;
use warnings;

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

, .

0

Source: https://habr.com/ru/post/1711100/


All Articles