Reputation: 405
I have a script which takes a relative path to a folder. Is there any way of getting the name of the folder/directory which is pointed to? If needs be, it could be the absolute path, and I will use regex to strip it.
Say I am executing:
/example/a/b/c/d/perl.pl
e.g. 1
If they input:
../../
I want it to be able to return 'b' (or the absolute path up to b, I can write a script to strip it).
e.g.2
If they input:
./
I want it to be able to return 'd' (or again, the absolute path up to d).
Is there an easy way to do this, as the only way I can think of is counting the number of ../
and using that to do a regex on the absolute path of the file, which takes alot of processing.
Thanks
Upvotes: 1
Views: 379
Reputation: 385496
Relative to the script being executed (as you requested):
use Cwd qw( realpath );
use File::Basename qw( dirname );
my $script_dir = dirname(realpath($0));
my $abs_path = real_path("$script_dir/$rel_path");
Relative to the current work directory:
use Cwd qw( realpath );
my $abs_path = realpath($rel_path);
In both cases, symlinks are resolved. File::Spec provides functions that don't resolve symlinks if that's what you prefer.
Upvotes: 2