lexicalscope
lexicalscope

Reputation: 7328

How do I convert a full path to a relative path using 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"

Upvotes: 13

Views: 6839

Answers (2)

aruparap
aruparap

Reputation: 101

use Path::Class;
my $full = file( "/full/path/to/my/file" );
my $relative = $full->relative( "/full" );

Upvotes: 10

parapura rajkumar
parapura rajkumar

Reputation: 24403

Use File::Spec

They have a abs2rel function

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

Will work on both Windows and Linux

Upvotes: 26

Related Questions