R – How to get the absolute path of the Perl program from its relative path

perlrelative-path

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!

Best Answer

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