Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a full path to a relative path using perl?

Tags:

perl

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"
like image 411
lexicalscope Avatar asked Nov 15 '11 13:11

lexicalscope


People also ask

How do you convert an absolute path to a relative path?

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.

How do you make a path relative?

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.

How do I get an absolute path in Perl?

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.

How do I specify a file path in Perl?

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.


2 Answers

Use File::Spec

They have a abs2rel function

my $relativePath = File::Spec->abs2rel ($filePath,  $parentPath);

Will work on both Windows and Linux

like image 169
parapura rajkumar Avatar answered Oct 26 '22 07:10

parapura rajkumar


use Path::Class;
my $full = file( "/full/path/to/my/file" );
my $relative = $full->relative( "/full" );
like image 26
aruparap Avatar answered Oct 26 '22 07:10

aruparap