How do I get the full path to a Perl script that is executing? – Right way.

  • THESE ALL WRONG !!!!!!
    use Cwd qw(abs_path cwd);
    my $cwd = cwd();
    my $abs_path = abs_path();
    my $FILE = __FILE__;
    print "1. $cwd $abs_path $FILE\n";
    
    
    
    use File::Basename;
    my $dirname = dirname(__FILE__);
    print "2. $dirname\n";
    
    use File::Spec;
    my $relabs = File::Spec->rel2abs( __FILE__ );
    print "3. $relabs\n";
    
    
  • so as it:

    user@it.sysnet.by [/var]# pwd
    /var
    sysnetb@it.sysnet.by [/var]# ../home/user/backups/run.pl
    1. /var /var ../home/user/backups/run.pl
    2. ../home/user/backups
    3. /var/../home/user/backups/run.pl
    user@it.sysnet.by [/var]#
    
  • Right Way
    my $good = `readlink -f $0`;
    print "4. $good\n";
    

    so as it:

    user@it.sysnet.by [/var]# pwd
    /var
    user@it.sysnet.by [/var]# ../home/user/backups/run.pl
    4. /home/user/backups/run.pl
    user@it.sysnet.by [/var]# 
    
  • Production version:
    use File::Basename;
    my $place = `readlink -f $0`;
    chomp($place);
    $place = dirname($place);
    print "$place\n";
    
Scroll to top