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

后端 未结 23 2784
情深已故
情深已故 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:54

    The problem with __FILE__ is that it will print the core module ".pm" path not necessarily the ".cgi" or ".pl" script path that is running. I guess it depends on what your goal is.

    It seems to me that Cwd just needs to be updated for mod_perl. Here is my suggestion:

    my $path;
    
    use File::Basename;
    my $file = basename($ENV{SCRIPT_NAME});
    
    if (exists $ENV{MOD_PERL} && ($ENV{MOD_PERL_API_VERSION} < 2)) {
      if ($^O =~/Win/) {
        $path = `echo %cd%`;
        chop $path;
        $path =~ s!\\!/!g;
        $path .= $ENV{SCRIPT_NAME};
      }
      else {
        $path = `pwd`;
        $path .= "/$file";
      }
      # add support for other operating systems
    }
    else {
      require Cwd;
      $path = Cwd::getcwd()."/$file";
    }
    print $path;
    

    Please add any suggestions.

    0 讨论(0)
  • 2020-11-28 19:55

    Without any external modules, valid for shell, works well even with '../':

    my $self = `pwd`;
    chomp $self;
    $self .='/'.$1 if $0 =~/([^\/]*)$/; #keep the filename only
    print "self=$self\n";
    

    test:

    $ /my/temp/Host$ perl ./host-mod.pl 
    self=/my/temp/Host/host-mod.pl
    
    $ /my/temp/Host$ ./host-mod.pl 
    self=/my/temp/Host/host-mod.pl
    
    $ /my/temp/Host$ ../Host/./host-mod.pl 
    self=/my/temp/Host/host-mod.pl
    
    0 讨论(0)
  • 2020-11-28 19:56

    On *nix, you likely have the "whereis" command, which searches your $PATH looking for a binary with a given name. If $0 doesn't contain the full path name, running whereis $scriptname and saving the result into a variable should tell you where the script is located.

    0 讨论(0)
  • 2020-11-28 19:57

    Have you tried:

    $ENV{'SCRIPT_NAME'}
    

    or

    use FindBin '$Bin';
    print "The script is located in $Bin.\n";
    

    It really depends on how it's being called and if it's CGI or being run from a normal shell, etc.

    0 讨论(0)
  • 2020-11-28 19:57

    There's no need to use external modules, with just one line you can have the file name and relative path. If you are using modules and need to apply a path relative to the script directory, the relative path is enough.

    $0 =~ m/(.+)[\/\\](.+)$/;
    print "full path: $1, file name: $2\n";
    
    0 讨论(0)
  • 2020-11-28 19:58

    In order to get the path to the directory containing my script I used a combination of answers given already.

    #!/usr/bin/perl
    use strict;
    use warnings;
    use File::Spec;
    use File::Basename;
    
    my $dir = dirname(File::Spec->rel2abs(__FILE__));
    
    0 讨论(0)
提交回复
热议问题