How to get the current working directory in Perl?
Question
How to get the current working directory in Perl?
How to Get the Current Working Directory in Perl
In Perl, the current working directory (CWD) is the directory from which your script is running or operating. It’s often needed when working with files or relative paths. The recommended and most portable way to get the current working directory is to use the cwd() function from Perl’s core Cwd module.
Using the Cwd Module
The Cwd module provides:
cwd(): Returns the absolute path of the current directory as a scalar stringgetcwd(): Usually an alias tocwd()
You must use Cwd; to import these functions before using them. This is a common pitfall—calling cwd() without importing Cwd will cause an error like Undefined subroutine &main::cwd.
Perl Sigils and Context
The cwd() function returns a scalar, which means you assign its result to a scalar variable with $. It works best in scalar context, returning a single string that contains the absolute path.
Example: Print Current Working Directory
use strict;
use warnings;
use Cwd;
# Get the current working directory
my $cwd = cwd();
print "Current working directory is: $cwd\n";
This script safely prints the absolute current directory path. Running this as perl - and pasting the code will execute without errors.
Common Pitfalls
- Not loading
Cwd:cwd()is not a built-in function without the module. - Using backticks: Avoid shelling out to
pwdfor portability and efficiency. - Confusing context or sigils: Remember
cwd()returns a scalar string, so store it in$variable.
Perl Version Notes
Cwd has been available in core Perl for decades (since at least 5.004). The interface to cwd() is stable and portable across all modern Perl versions (5.8+).
Summary
In summary, to reliably get the current working directory in Perl, always use Cwd; and then call cwd() in scalar context. This approach avoids portability issues and errors, providing a clean and simple way to retrieve the absolute path of your working directory.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 16ms
Current working directory is: /Volumes/SSD/skills/server-ops/vps/107.174.42.198/Standalone-Apps/perlcode
(empty)Was this helpful?
Related Questions
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?