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 di
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;
Use:
print($ENV{'PWD'});
But I think it doesn't work on Windows...
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.
Here is one simple solution:
use Cwd;
my $cwd = cwd();
print "Current working directory: '$cwd()'";
I hope this will help.
Just remove the '$0'
use Cwd qw(abs_path);
my $path = abs_path();
print "$path\n";
I used my script in dirs with symlinks. The script parses the path and executes commands depending on the path. I was faced with the correct determination of the current path.
Here is example:
root@srv apache # pwd
/services/apache
root@srv apache # readlink -f .
/services/apache2225
Cwd module disclosures path (analogue of readlink -f) http://perldoc.perl.org/Cwd.html
root@server apache # perl -e 'use Cwd; print cwd . "\n";'
/services/apache2225
If you need to get current path like pwd, you can use $ENV{'PWD'}
root@srv apache # perl -e 'use Cwd; print $ENV{'PWD'}."\n";'
/services/apache
Thank you.