Search code examples
perlgnu-coreutils

Perl command for same behaviour as readlink?


What is the equivalent Perl command to the GNU coreutils command readlink -f?

If any component of the file name except the last one is missing or unavailable, readlink produces no output and exits with a nonzero exit code. A trailing slash is ignored.


Solution

  • You can use Cwd:

    use Cwd 'abs_path';
    my $path = "/some/arbitrary/path";
    print abs_path($path);
    

    Test:

    for q in exists imaginary imarginary/imaginary ; do
       echo "$q"
       echo -n "readlink -f: " ; readlink -f "$q"
       echo -n "abs_path:    " ; perl -MCwd=abs_path -E'say abs_path $ARGV[0]' "$q"
       echo
    done
    

    Output:

    exists
    readlink -f: /home/eric/exists
    abs_path:    /home/eric/exists
    
    imaginary
    readlink -f: /home/eric/imaginary
    abs_path:    /home/eric/imaginary
    
    imaginary/imaginary
    readlink -f: abs_path: