Scott Holtzman
Scott Holtzman

Reputation: 27239

get directory of active perl file

I working with perl and have a file saved in directory like so:

/root/dir_1/dir_2/dir_3/dir_4/perl_file.pl

What I am trying to do from within the perl file itself is to get the string of /root ... dir_4/ or just dir_4/ so I can then use that to make another directory (there's a specific pattern I can use to make the new directory).

I have been looking at File::Copy and File::Basename which seem to require you to specify the path, but I want my path to be variable based on the file that is run. It seems very simple and probably something I am just overlooking, but is this possible?

In pseudo-code, I am looking for something like my $dir = UpOneDirectory(thisperlfile) or FilePath(thisperlfile)

Upvotes: 0

Views: 323

Answers (3)

Tim Peoples
Tim Peoples

Reputation: 354

...or... if you don't want to depend on an external module, you can do this with a one-line regex substitution:

(my $me = $0) =~ s#(^/.*?)/?[^/]*$#\1#;

This will assign a string value to $me that represents the path to the directory containing the current script.

Here's how it works. $0 contains the path to the currently executing script. We want to assign it to $me but we also want to manipulate it with a regex substitution, so we put the assignment inside parenthesis (note, the "my" declaration must go inside the parens as well (or perl will barf)).

The regex matches the initial '/' followed by all characters up to the final '/' and then all non '/' characters to the end of the string (note: the regex is anchored on both ends using '^' and '$'). A grouping set is then used to substitute everything up to (but not including) the final '/' as the new string value. IOW: the directory component of the path.

Also note that all this extra fluff is simply to deal with the case where a file resides in the root directory and we want the result to actually be '/' (instead of ''). If we didn't need to cover this case, the regex could be much simpler, like so:

(my $me = $0) =~ s#/[^/]*$##; # DON'T USE THIS ONE  (Use the above example instead)

...but that doesn't cover all the bases.

Upvotes: 0

jkshah
jkshah

Reputation: 11703

use File::Basename;
use Cwd qw( abs_path );

my $dir = dirname(abs_path($0));

Upvotes: 1

ikegami
ikegami

Reputation: 385506

use FindBin qw( $RealBin );
say $RealBin;

Upvotes: 5

Related Questions