How can I resolve a symbolic link in Perl?

别来无恙 提交于 2019-12-05 20:32:16

First of all, are you sure that you don't want to use ${JAVA_HOME} environment variable?

You can read the symlink target using builtin readlink() function.

To check other possibilities, you may either hardcode them all and check one by one for existence, use opendir() / readdir() builtins or objective IO::Dir to lookup all the symlinks in the directory and check whether they match or pattern, or even glob() function which may be simpler in your case.

Mohamed Samy
use Cwd 'abs_path';

$absFilePath = abs_path("$linkPath") ;

Here is the solution for the linked files or soft link files. the following snippet will give the original file of the link, by resolving all links recursively

#!/usr/bin/perl

use warnings;
use strict;

use File::Basename;

my $file='/dev/mapper/vg_ms1-lv_root'; #this should be your input
my $myCwd =`pwd`;
chomp($myCwd);

while ( -l $file ) {
    my $readLnk=readlink( $file );
    #print "$readLnk\n";
    my $directory = dirname( $file );
    my $fileName = basename( $file ); #not doing anything with this name
    #print "$directory\n";
    chdir($directory);
    my $linkPDir = dirname( $readLnk );
    chdir($linkPDir);
    my $next_file = basename( $readLnk );
    my $curDir=`pwd`;
    chomp($curDir);
    $file="$curDir"."/"."$next_file";
}

print "$file\n";
chdir($myCwd);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!