I have the full path to a file and the full path to one of its parent directories in two variables in Perl program.
What is a safe way to calculate the relative path of the file relative to the parent directory. Needs to work on windows and unix.
e.g.
$filePath = "/full/path/to/my/file";
$parentPath = "/full";
$relativePath = ??? # should be "path/to/my/file"
The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.
Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.
use File::Spec; ... my $rel_path = 'myfile. txt'; my $abs_path = File::Spec->rel2abs( $rel_path ) ; ... and if you actually need to search through your directories for that file, there's File::Find... but I would go with shell find / -name myfile. txt -print command probably.
You specify the pathname in the manner in which your operating system expects it, as shown in the following examples: open(MYFILE, "DISK5:[USER. PIERCE. NOVEL]") || die; # VMS open(MYFILE, "Drive:folder:file") || die; # Macintosh open(MYFILE, "/usr/pierce/novel") || die; # Unix.
Use File::Spec
They have a abs2rel function
my $relativePath = File::Spec->abs2rel ($filePath, $parentPath);
Will work on both Windows and Linux
use Path::Class;
my $full = file( "/full/path/to/my/file" );
my $relative = $full->relative( "/full" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With