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#

  • Empty string or no argument — treated as ..

  • 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.

  • Both leaf and parent missing — returns undef.

  • Symlink loop — returns undef and sets $! to ELOOP.

Differences from upstream#

  • The leaf-fallback form is always available; upstream provides it only via _perl_abs_path when the XS path is not loaded.

  • realpath is wired to the same implementation as abs_path, matching upstream’s *realpath = \&abs_path alias.

See also#

  • fast_abs_path — same canonicalisation, no leaf fallback

  • getcwd — absolute path of the current directory only

  • chdir — change directory before resolving relative paths