7

# 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 ?

Tree
  • 9,532
  • 24
  • 64
  • 83
  • are you saying you want the absolute path of the symlink or the absolute path of the file the symlink points to? – ian Feb 03 '11 at 15:04
  • 1
    absolute path of the file the symlink points to – Tree Feb 03 '11 at 15:07
  • So actually you just want to know how to get the absolute path for a given pathname, because you already know how to use `readlink()` to get a path to the pointed-to file. – j_random_hacker Feb 03 '11 at 15:11
  • 2
    See http://stackoverflow.com/questions/1527638/what-perl-modules-do-i-use-to-obtain-an-absolute-path-including-filename-from/1527773#1527773. (In a sense your question is a dupe of this since brian's answer is the right answer for any OS, not just Windows.) – j_random_hacker Feb 03 '11 at 15:14

2 Answers2

12

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);
}
A.I
  • 1,438
  • 2
  • 16
  • 18
thevilledev
  • 2,367
  • 1
  • 15
  • 19
  • Carefull, that will likely go wrong when UTF-8 filenames are in use. In that case something like `Encode::decode_utf8(Cwd::abs_path($file));` may be needed! – Gerd K Jan 16 '17 at 16:23
2

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) ) ;
ian
  • 12,003
  • 9
  • 51
  • 107
  • File::Spec's rel2abs doesn't seem to work with multiple links. Cwd's abs_path works. Try `touch /tmp/target; ln -s target /tmp/link1; ln -s link1 /tmp/link2` and compare `perl -MFile::Spec -e '$f="/tmp/link2"; print "$f: ", File::Spec->rel2abs( readlink($f) ), "\n"'`with `perl -M'Cwd "abs_path"' -e '$f="/tmp/link2"; print "$f : ", abs_path($f), "\n"'` – mivk Apr 26 '12 at 10:56
  • Thanks for proving that specifying soft links without the path prefix when you're not in the same directory will break things and is, therefore, a bad thing to do ;-) – ian Apr 26 '12 at 12:48
  • 1
    Should I also point out that the OP asked for the ["absolute path of the file the symlink points to"](http://stackoverflow.com/questions/4887672/how-to-get-the-absolute-path-for-symlink-file#comment-5437184) and *not* the canonical path (which is an absolute path but _not necessarily_ the file asked for)? – ian Apr 26 '12 at 13:00