如何使用perl将完整路径转换为相对路径?

lex*_*ope 13 perl

我有一个文件的完整路径和Perl程序中两个变量中其父目录之一的完整路径.

什么是计算文件相对于父目录的相对路径的安全方法.需要在windows和unix上工作.

例如

$filePath = "/full/path/to/my/file";
$parentPath = "/full";
$relativePath = ??? # should be "path/to/my/file"
Run Code Online (Sandbox Code Playgroud)

par*_*mar 23

使用File :: Spec

它们具有abs2rel功能

my $relativePath = File::Spec->abs2rel ($filePath,  $parentPath);
Run Code Online (Sandbox Code Playgroud)

适用于Windows和Linux


小智 9

use Path::Class;
my $full = file( "/full/path/to/my/file" );
my $relative = $full->relative( "/full" );
Run Code Online (Sandbox Code Playgroud)

  • +1我喜欢[Path :: Class](http://p3rl.org/Path::Class),它在File :: Spec中引用了一些设计瑕疵. (3认同)