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

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

    On Windows using dirname and abs_path together worked best for me.

    use File::Basename;
    use Cwd qw(abs_path);
    
    # absolute path of the directory containing the executing script
    my $abs_dirname = dirname(abs_path($0));
    print "\ndirname(abs_path(\$0)) -> $abs_dirname\n";
    

    here's why:

    # this gives the answer I want in relative path form, not absolute
    my $rel_dirname = dirname(__FILE__); 
    print "dirname(__FILE__) -> $rel_dirname\n"; 
    
    # this gives the slightly wrong answer, but in the form I want 
    my $full_filepath = abs_path($0);
    print "abs_path(\$0) -> $full_filepath\n";
    

提交回复
热议问题