Perl file test - How to determine whether you can read a file

Perl file test FAQ: How can I run a Perl test to see if I have read access on a file?

Using Perl it’s simple to determine whether you can read a file. Just use the -r file test operator, as shown in this example:

$filename = 'tempfile.pl';

if (-r $filename) {
    print "i can read the file\n";
} else {
    print "i can't read the file!\n";
}

Effective uid/gid versus real uid/gid

Note that the Perl -r test operator uses the effective uid or gid of the current user when making this determination. If for some reason you need to perform this file test with the real uid or gid of the current user, you would use the -R test, like this:

$filename = 'tempfile.pl';

if (-R $filename) {
    print "i can read the file\n";
} else {
    print "i can't read the file!\n";
}

I almost always use the first Perl file test — in fact, I don’t remember ever using the second test — but I thought I better mention this in case you run into any problems.