joybee2015 has asked for the wisdom of the Perl Monks concerning the following question:


Hello and thanks for your help!
Here is the problem I have:

In /var/tmp, I have file1, file2 and flink and flink ->file1, I need to get the absolute path of file1, which is /var/tmp/file1 to compare it with string fp1, the problem is that I cant get absolute path, how to solve the issue?

#!/usr/bin/perl my $lpath = /var/tmp/flink; my $fp1 = /var/tmp/file1; my $realpath =readlink($lpath); #which returns file1; my $absolutepath = abs_path($realpath); #returns ~/perl/file1, where ~ +/perl is where my perl script is, not correct if (-e $realpath) { print "$realpath exist\n"; } else { print "not exist\n"; #which is not true }

Should I parse the $realpath, if there is no "/" or if it starts with "./", get the directory path from $lpath?

Replies are listed 'Best First'.
Re: symbolic link and absolute path
by ikegami (Patriarch) on Aug 07, 2017 at 20:39 UTC

    In contradiction to what you claim, that code doesn't run. I'm going to assume you imported abs_path refers to abs_path from Cwd.

    abs_path takes a path relative to the current work directory and converts it into an absolute path.

    However, readlink returns a path that should be treated as relative to the directory in which the symbolic link is found.

    You could use a means of finding the absolute path that allows you to specify the base directory, but there's a simpler solution here:

    my $absolutepath = abs_path($lpath);
Re: symbolic link and absolute path
by 1nickt (Canon) on Aug 07, 2017 at 20:53 UTC

    You don't need readlink. Simply use abs_path.

    $ cd /Users/nick $ echo 'hi' > /tmp/foo $ ln -s /tmp/foo ./foo $ perl -MCwd=abs_path -E 'say abs_path("./foo")' /private/tmp/foo $ perl -MCwd=abs_path -E 'say abs_path("/Users/nick/foo")' /private/tmp/foo


    The way forward always starts with a minimal test.

      Thanks ikegami and lnickt for the help. Using abs_path directly without readlink did solve the problem.

      And sorry for the bug in my program. I posted on the windows and I ran my code on linux. So I just typed the code here without checking. I indeed used Cwd qw(abs_path).