Check if directory exists in ~/ using Perl

27,243

Solution 1

~ is a shell shortcut to indicate the home directory, it is unknown to perl. You have to use the environment variable HOME here -- for instance using "$ENV{HOME}/my_dir".

Solution 2

~ is not a real path. Shells such as /bin/bash expand it to the value of the $HOME environment variable. Perl does not. So, you should use something like this instead:

if ( -d "$ENV{HOME}/my_dir" ) {
    ...
}
Share:
27,243
Ricky Levi
Author by

Ricky Levi

Updated on May 29, 2020

Comments

  • Ricky Levi
    Ricky Levi almost 4 years

    I noticed strange behavior of the -d flag to check if a file is a directory and if the directory exists. It behaves differently when using ~/my_dir as my path.

    The following code will return false, even though the directory my_dir exists, but if I'll change it to a full path like /home/ricky/my_dir, then the if statement will return true.

    #!/usr/bin/perl -w
    #
    use strict;
    
    if ( -d "~/my_dir") {
        print "Found \n";
    }
    else {
        print "Not found \n";
    }
    

    What's the difference?

  • Ricky Levi
    Ricky Levi almost 11 years
    BTW, using system vs back-ticks makes ~/ work in the 'system' function, which is also a difference that I just found ... ( also symlinks have the same issue ) - thanks for the answer :)
  • ikegami
    ikegami almost 11 years
    Unknown to the system, even. Perl doesn't do anything with the path but pass it to the system.
  • aschepler
    aschepler over 9 years
    @Ricky That's because the system function runs a /bin/sh, which will do its shell substitutions on your command line.
  • Ricky Levi
    Ricky Levi over 9 years
    @aschepler I just run system('echo $SHELL'); and it says /bin/bash .. so I'm not sure this is correct.
  • aschepler
    aschepler over 9 years
    That's just the environment variable. Try system(q(ps $$)).
  • Ricky Levi
    Ricky Levi over 9 years
    @aschepler I'm not sure what I'm suppose to see ... this is the output 17507 pts/0 R+ 0:00 ps 17507
  • Keith Thompson
    Keith Thompson almost 9 years
    -d is the correct way to tell whether a directory exists. chdir has the side effect of changing to the directory; it will also fail if dir_name is a directory but you don't have permission to change to it. And this doesn't address the OP's problem, which is the use of ~.