Tree
Tree

Reputation: 10342

how to get the Absolute Path for symlink file?

# test-> a.pl

my $file = '/home/joe/test';
if ( -f $file && -l $file )  {
    print readlink( $file ) ;
}

how to get the Absolute Path for symlink file ?

Upvotes: 9

Views: 17072

Answers (3)

Richard Miao CN
Richard Miao CN

Reputation: 1

use File::Basename qw( dirname );
use Cwd qw( abs_path );

    if (-l $file) {
        $file = abs_path(dirname($file).'/'.readlink($file));
    }

Upvotes: -1

thevilledev
thevilledev

Reputation: 2377

Cwd provides such functionality by abs_path.

#!/usr/bin/perl -w

use Cwd 'abs_path';

my $file='/home/joe/test';
if( -f $file && -l $file ) {
    print abs_path($file);
}

Upvotes: 12

ian
ian

Reputation: 12251

if you use File::Spec rel2abs along with readlink you'll get the abs path even if it's a symlink to another symlink

use File::Spec;

$path = File::Spec->rel2abs( readlink($file) ) ;

Upvotes: 2

Related Questions