Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if directory exists in ~/ using Perl

Tags:

directory

perl

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?

like image 577
Ricky Levi Avatar asked May 23 '13 15:05

Ricky Levi


People also ask

How do you create directory in Perl If not exist?

The make_path function creates the given directories if they don't exist before, much like the Unix command mkdir -p . The function accepts a list of directories to be created.

How do I change directory in Perl?

You can use chdir function in Perl to change a directory and go to a new location. You will need to have the required permission to change a directory and go inside the new directory.


1 Answers

~ 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".

like image 145
fge Avatar answered Sep 27 '22 21:09

fge