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
eg 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).
eg2
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
That's simple - just use Cwd module:
use Cwd 'abs_path';
my $abs_path = abs_path($file);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.