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: [/var]# pwd
    /var [/var]# ../home/user/backups/
    1. /var /var ../home/user/backups/
    2. ../home/user/backups
    3. /var/../home/user/backups/ [/var]#
  • Right Way
    my $good = `readlink -f $0`;
    print "4. $good\n";

    so as it: [/var]# pwd
    /var [/var]# ../home/user/backups/
    4. /home/user/backups/ [/var]# 
  • Production version:
    use File::Basename;
    my $place = `readlink -f $0`;
    $place = dirname($place);
    print "$place\n";

Leave a Reply

Your email address will not be published. Required fields are marked *


Scroll to top