Print current directory using Perl

后端 未结 7 2153
走了就别回头了
走了就别回头了 2020-12-29 05:53

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

相关标签:
7条回答
  • 2020-12-29 06:00

    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;
    
    0 讨论(0)
  • 2020-12-29 06:01

    Use:

    print($ENV{'PWD'});
    

    But I think it doesn't work on Windows...

    0 讨论(0)
  • 2020-12-29 06:05

    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.

    0 讨论(0)
  • 2020-12-29 06:13

    Here is one simple solution:

        use Cwd;
        my $cwd = cwd();
        print "Current working directory: '$cwd()'";
    

    I hope this will help.

    0 讨论(0)
  • 2020-12-29 06:17

    Just remove the '$0'

    use Cwd qw(abs_path);
    my $path = abs_path();
    print "$path\n";
    
    0 讨论(0)
  • 2020-12-29 06:22

    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.

    0 讨论(0)
提交回复
热议问题