How do I get the full path to a Perl script that is executing?

后端 未结 23 2783
情深已故
情深已故 2020-11-28 19:29

I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script $0 va

相关标签:
23条回答
  • 2020-11-28 19:59

    perlfaq8 answers a very similar question with using the rel2abs() function on $0. That function can be found in File::Spec.

    0 讨论(0)
  • 2020-11-28 20:00
    use File::Basename;
    use Cwd 'abs_path';
    print dirname(abs_path(__FILE__)) ;
    

    Drew's answer gave me:

    '.'

    $ cat >testdirname
    use File::Basename;
    print dirname(__FILE__);
    $ perl testdirname
    .$ perl -v
    
    This is perl 5, version 28, subversion 1 (v5.28.1) built for x86_64-linux-gnu-thread-multi][1]
    
    0 讨论(0)
  • 2020-11-28 20:04
    #!/usr/bin/perl -w
    use strict;
    
    
    my $path = $0;
    $path =~ s/\.\///g;
    if ($path =~ /\//){
      if ($path =~ /^\//){
        $path =~ /^((\/[^\/]+){1,}\/)[^\/]+$/;
        $path = $1;
        }
      else {
        $path =~ /^(([^\/]+\/){1,})[^\/]+$/;
        my $path_b = $1;
        my $path_a = `pwd`;
        chop($path_a);
        $path = $path_a."/".$path_b;
        }
      }
    else{
      $path = `pwd`;
      chop($path);
      $path.="/";
      }
    $path =~ s/\/\//\//g;
    
    
    
    print "\n$path\n";
    

    :DD

    0 讨论(0)
  • 2020-11-28 20:04

    Are you looking for this?:

    my $thisfile = $1 if $0 =~
    /\\([^\\]*)$|\/([^\/]*)$/;
    
    print "You are running $thisfile
    now.\n";
    

    The output will look like this:

    You are running MyFileName.pl now.
    

    It works on both Windows and Unix.

    0 讨论(0)
  • 2020-11-28 20:04

    None of the "top" answers were right for me. The problem with using FindBin '$Bin' or Cwd is that they return absolute path with all symbolic links resolved. In my case I needed the exact path with symbolic links present - the same as returns Unix command "pwd" and not "pwd -P". The following function provides the solution:

    sub get_script_full_path {
        use File::Basename;
        use File::Spec;
        use Cwd qw(chdir cwd);
        my $curr_dir = cwd();
        chdir(dirname($0));
        my $dir = $ENV{PWD};
        chdir( $curr_dir);
        return File::Spec->catfile($dir, basename($0));
    }
    
    0 讨论(0)
提交回复
热议问题