Print current directory using Perl

Each of the following snippets get the script's directory, which is not the same as the current directory. It's not clear which one you want.

use FindBin qw( $RealBin );

say $RealBin;

or

use Cwd            qw( abs_path );
use File::Basename qw( dirname );

say dirname(abs_path($0));

or

use Cwd         qw( abs_path );
use Path::Class qw( file );

say file(abs_path($0))->dir;

To get the current working directory (pwd on many systems), you could use cwd() instead of abs_path:

use Cwd qw();
my $path = Cwd::cwd();
print "$path\n";

Or abs_path without an argument:

use Cwd qw();
my $path = Cwd::abs_path();
print "$path\n";

See the Cwd docs for details.

To get the directory your perl file is in from outside of the directory:

use File::Basename qw();
my ($name, $path, $suffix) = File::Basename::fileparse($0);
print "$path\n";

See the File::Basename docs for more details.

Tags:

Perl

Directory