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 undef with $! set to ENOENT.

  • 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 Cwd with no import list.

Differences from upstream#

  • cwd, getcwd, fastcwd, and fastgetcwd all call the kernel’s getcwd(3) directly. Upstream fastcwd walks the tree with repeated chdir('..') 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 CWD

  • chdir — change directory and keep $ENV{PWD} synchronised

  • realpath — POSIX-style alias for abs_path