abs_path#

Canonicalise a path: resolve symlinks, ., and .., and return the absolute form.

Synopsis#

use Cwd qw(abs_path realpath);
my $abs = abs_path($path);
my $abs = realpath($path);    # same function, POSIX alias
my $abs = abs_path();         # defaults to current directory

What you get back#

A plain Perl string: the absolute, symlink-free path. On unresolvable input returns undef and sets $!. If the leaf component does not exist but its parent does, the parent is canonicalised and the leaf is appended verbatim - useful for computing where a file would be written.

Examples#

Resolve a relative path against the current directory:

use Cwd qw(abs_path);
chdir '/home/alice' or die $!;
print abs_path('project/Makefile'), "\n";
    # /home/alice/project/Makefile

Follow a symlink to its target:

use Cwd qw(abs_path);
symlink '/etc/hostname', '/tmp/link';
print abs_path('/tmp/link'), "\n";     # /etc/hostname

Compute the absolute path a file would have before creating it:

use Cwd qw(abs_path);
print abs_path('output.new'), "\n";
    # e.g. /home/alice/project/output.new - even if output.new
    # does not yet exist, as long as the directory does

Use realpath when the surrounding code expects the POSIX name:

use Cwd qw(realpath);
print realpath('.'), "\n";      # absolute path of current dir

Edge cases#

  • No argument - treated as .. An empty string resolves to the current directory too.

  • Leaf missing, parent present - returns parent’s canonical path joined with the leaf name. fast_abs_path returns undef in this situation; use it when “doesn’t exist” should be an error.

  • An inner component missing - returns undef.

  • A chain of more than 21 symlinks - undef, $! set to ELOOP.

  • The path is taken as bytes: a name that is not UTF-8 comes back unchanged.

  • Under taint mode the result is tainted.

See also#

  • fast_abs_path - same canonicalisation, no leaf fallback

  • getcwd - absolute path of the current directory only