cwd#
Return the absolute path of the process’s current working directory.
Synopsis#
use Cwd;
my $dir = getcwd();
my $dir = cwd();
my $dir = fastcwd();
my $dir = fastgetcwd();
What you get back#
A plain Perl string: the absolute path, no trailing newline, no
trailing slash (except when you really are at the root /). On
failure every variant returns undef and sets $!.
Examples#
Print where the script is running from:
use Cwd;
print getcwd(), "\n"; # e.g. /home/alice/project
Save and restore the working directory around a block that
chdirs:
use Cwd;
my $saved = getcwd();
chdir '/tmp' or die $!;
## ... do work in /tmp ...
chdir $saved or die $!;
Compare two paths by their canonical form:
use Cwd;
chdir '/var/log' or die $!;
print getcwd() eq '/var/log' ? "yes\n" : "no\n"; # yes
Edge cases#
If the current directory has been removed by another process, every variant returns
undefwith$!set toENOENT.Symlinks in the path are already resolved by the kernel’s
getcwd(3); the returned string is the real path.All four names are provided by default when you
use Cwdwith no import list.
Differences from upstream#
cwd,getcwd,fastcwd, andfastgetcwdall call the kernel’sgetcwd(3)directly. Upstreamfastcwdwalks the tree with repeatedchdir('..')and can leave the process in a different directory on failure; pperl’s version never chdirs and therefore cannot strand the process. The “Unstable directory path” die from upstream does not occur.
See also#
abs_path— canonicalise an arbitrary path, not just the CWDchdir— change directory and keep$ENV{PWD}synchronisedrealpath— POSIX-style alias forabs_path