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_pathreturnsundefin this situation; use it when “doesn’t exist” should be an error.Both leaf and parent missing — returns
undef.Symlink loop — returns
undefand sets$!toELOOP.
Differences from upstream#
The leaf-fallback form is always available; upstream provides it only via
_perl_abs_pathwhen the XS path is not loaded.realpathis wired to the same implementation asabs_path, matching upstream’s*realpath = \&abs_pathalias.
See also#
fast_abs_path— same canonicalisation, no leaf fallbackgetcwd— absolute path of the current directory onlychdir— change directory before resolving relative paths