通过保留符号链接获取 perl 的可执行绝对路径 [英] Getting perl's executable absolute path with keeping symlinks

查看:68
本文介绍了通过保留符号链接获取 perl 的可执行绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在保留符号链接的情况下获取 perl 可执行文件的清理后的绝对路径?(来自 $^X 变量或无论如何)

How to get the cleaned-up absolute path for the perl's executable but with keeping symlinks? (From the $^X variable or anyhow)

示例 perl 可执行文件:

example perl executable:

$ ls -l /opt/local/bin/perl
lrwxr-xr-x  1 root  admin  8 18 nov 02:46 /opt/local/bin/perl -> perl5.12

无论我如何运行 perl 解释器,我都希望在我的脚本中获得 /opt/local/bin/perl.

I want get /opt/local/bin/perl in my script regardless how I run the perl interpreter.

测试代码(changesbang.pl):

The testing code (changesbang.pl):

use strict;
use warnings;
use Cwd;
use File::Spec;
use Config;

my $fmt = "%-25s: %s\n";

printf $fmt, "The value of ^X",        $^X;

printf $fmt, "Cwd::realpath",          Cwd::realpath($^X);
printf $fmt, "Cwd::abs_path",          Cwd::abs_path($^X);

printf $fmt, "File::Spec->cannonpath", File::Spec->canonpath($^X);
printf $fmt, "File::Spec->rel2abs",    File::Spec->rel2abs($^X);

printf $fmt, "Config{perlpath}",       $Config{perlpath};

现在运行上面的代码

$ ../../../../../opt/local/bin/perl changesbang.pl
The value of ^X          : ../../../../../opt/local/bin/perl
Cwd::realpath            : /opt/local/bin/perl5.12
Cwd::abs_path            : /opt/local/bin/perl5.12
File::Spec->cannonpath   : ../../../../../opt/local/bin/perl
File::Spec->rel2abs      : /Users/jm/Develop/perl/changesbang/../../../../../opt/local/bin/perl
Config{perlpath}         : /opt/local/bin/perl5.12

没有人给我想要的/opt/local/bin/perl

问题是:如何通过约束获得想要的 perl 的可执行路径:

The question is: how to get the wanted perl's executable path with constrains:

  • 应该清理绝对路径
  • 但是如果它是符号链接,应该保留它(不要将其更改为它的目标)

Ps:这里有类似的问题,例如thisthis 但没有人给我回答.

Ps: Here are similar questions like this or this but no one gives me answer.

推荐答案

建议你试试

use File::Spec::Functions qw( rel2abs canonpath );

print canonpath(rel2abs($^X));

或者,还有

use Cwd::Ext 'abs_path_nd';

print abs_path_nd($^X);

这篇关于通过保留符号链接获取 perl 的可执行绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆