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

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

    All the library-free solutions don't actually work for more than a few ways to write a path (think ../ or /bla/x/../bin/./x/../ etc. My solution looks like below. I have one quirk: I don't have the faintest idea why I have to run the replacements twice. If I don't, I get a spurious "./" or "../". Apart from that, it seems quite robust to me.

      my $callpath = $0;
      my $pwd = `pwd`; chomp($pwd);
    
      # if called relative -> add pwd in front
      if ($callpath !~ /^\//) { $callpath = $pwd."/".$callpath; }  
    
      # do the cleanup
      $callpath =~ s!^\./!!;                          # starts with ./ -> drop
      $callpath =~ s!/\./!/!g;                        # /./ -> /
      $callpath =~ s!/\./!/!g;                        # /./ -> /        (twice)
    
      $callpath =~ s!/[^/]+/\.\./!/!g;                # /xxx/../ -> /
      $callpath =~ s!/[^/]+/\.\./!/!g;                # /xxx/../ -> /   (twice)
    
      my $calldir = $callpath;
      $calldir =~ s/(.*)\/([^\/]+)/$1/;
    

提交回复
热议问题