mac mac - 15 days ago 4
Perl Question

Print current directory using Perl

I have this code to print the current directory using Perl:

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


But it is displaying the filename of my script along with the directory.

Like this:


C:\Perl\duration.pl


I want it only to display
C:\Perl\
.

How can I do it?

Answer

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

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

say dirname(abs_path($0));

or

use Path::Class qw( file );

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

or

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

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

The middle one handles symlinks different than the other two, I believe.