Stefano
Stefano

Reputation: 85

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

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

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

Upvotes: 4

Views: 2124

Answers (1)

ikegami
ikegami

Reputation: 385685

-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

Upvotes: 11

Related Questions