File::Pathabsolute
不做任何文件系统检查。
use File::Path qw( file );
my $link_qfn = file(...);
my $link_dir_qfn = $link_qfn->dir;
my $target_qfn = $link_dir_qfn->file(readlink($link_qfn));
my $target_fqfn = $target_qfn->absolute;
say $target_fqfn;
说 CWD 是/tmp/perl_script_test/test
$link_qfn ../dir1/link1
$link_dir_qfn ../dir1
$target_qfn ../dir1/../dir2/link2
$target_fqfn /tmp/perl_script_test/test/../dir1/../dir2/link2
说 CWD 是/tmp/perl_script_test
$link_qfn dir1/link1
$link_dir_qfn dir1
$target_qfn dir1/../dir2/link2
$target_fqfn /tmp/perl_script_test/dir1/../dir2/link2
您已将以下内容添加到您的问题中:
我正在寻找没有 ../ 的符号链接直接目标的绝对路径
如果没有可能解决符号链接,您将无法安全地做到这一点。例如,
/tmp/perl_script_test/dir1/../dir2/link2
不一定等同于
/tmp/perl_script_test/dir2/link2
因为
/tmp/perl_script_test/dir1
可能是符号链接。
以下内容对您来说可能就足够了:
use Cwd qw( real_path );
use File::Path qw( dir file );
my $link_qfn = file(...);
my $link_dir_qfn = $link_qfn->dir;
my $target_qfn = $link_dir_qfn->file(readlink($link_qfn));
my $target_fn = $target_qfn->basename;
my $target_dir_qfn = $target_qfn->dir;
my $target_dir_fqfn = dir(real_path($target_dir_qfn));
my $target_fqfn = $target_dir_fqfn->file($target_fn);
say $target_fqfn;
说 CWD 是/tmp/perl_script_test/test
$link_qfn ../dir1/link1
$link_dir_qfn ../dir1
$target_qfn ../dir1/../dir2/link2
$target_fn link2
$target_dir_qfn ../dir1/../dir2
$target_dir_fqfn /tmp/perl_script_test/dir2
$target_fqfn /tmp/perl_script_test/dir2/link2
如果以下都不是符号链接,您将仅获得上述输出:
/tmp
/tmp/perl_script_test
/tmp/perl_script_test/test
/tmp/perl_script_test/dir1
/tmp/perl_script_test/dir2
(即使前两个是符号链接,你也可以让它工作,但这需要更多的工作。)