Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Can I get paths related to where a script resides and where it was executed from?

I'm looking for a way to get two pieces of information:

  • The full path of where a script resides including its filename
  • The full path of where a script was executed from

I know you can use $0 to get the file name, but are there any other reserved variables that are native to Perl that will give me what I'm looking for?

I'd rather not use any special modules, but if it is the only way, then so be it.

like image 251
CheeseConQueso Avatar asked Jan 26 '11 20:01

CheeseConQueso


1 Answers

Using FindBin and Cwd:

#!/usr/bin/env perl

use strict;
use warnings;

use Cwd        ();
use FindBin    ();
use File::Spec ();

my $full_path = File::Spec->catfile( $FindBin::Bin, $FindBin::Script );
my $executed_from_path = Cwd::getcwd();

print <<OUTPUT;
Full path to script: $full_path
Executed from path:  $executed_from_path
OUTPUT

Sample output (script saved as /tmp/test.pl):

alanhaggai@love:/usr/share$ /tmp/test.pl 
Full path to script: /tmp/test.pl
Executed from path:  /usr/share
like image 179
Alan Haggai Alavi Avatar answered Sep 28 '22 15:09

Alan Haggai Alavi