Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: How to distinguish if file does not exists or I don't have permissions to the path

Tags:

unix

perl

I need to test if a file/directory exists on the filesystem using Perl in a unix environment. I tried using the file test -e, but that does not distinguish between

  • The file/directory does not exist.
  • You don't have permission to read in the parent folder.

I could check what is in the $? variable after the test and search for "Permission denied", but it doesn't sound like the right thing to do.

Any advice?

Thanks a lot

like image 379
Stefano Avatar asked Dec 19 '22 15:12

Stefano


1 Answers

-e is just a call to stat, and like other systems calls, it sets $! and %! when it returns false.

if (-e $qfn) {
    print "ok\n";
}
elsif ($!{ENOENT}) {
    print "Doesn't exist\n";
}
else {
    die $!;
}

For example,

$ mkdir foo

$ touch foo/file

$ chmod 0 foo

$ perl x.pl foo/file
Permission denied at x.pl line 10.

$ perl x.pl bar/file
Doesn't exist

$ perl x.pl x.pl
ok
like image 123
ikegami Avatar answered May 10 '23 22:05

ikegami