How to check if a file is readable in Perl?
Question
How to check if a file is readable in Perl?
In Perl, checking whether a file is readable is commonly done using the -r file test operator. This operator tests if the file is readable by the effective user ID of the process running the script.
Why use -r file test operator?
-rreturns true if the file exists and your script has read permission.- It is concise, Perl-specific, and recommended over manually opening the file just to check read access.
- Works on any platform Perl supports (Unix, Windows), respecting the OS permissions.
Basic syntax
You use -r directly before the filename, like this:
if (-r $filename) {
print "We can read $filename\n";
} else {
print "Cannot read $filename\n";
}
Important Perl concepts illustrated
- File test operators like
-r,-w,-x, provide direct, readable checks for file attributes. - Scalar context: The operator expects a scalar filename.
- TMTOWTDI ("There's more than one way to do it"): You could also try opening the file and catching errors, but
-ris more straightforward.
Common pitfalls
- Remember
-rtests read permission for the real/effective UID of your script, not necessarily the owner or group of the file unless you run Perl with different privileges. - Checking if readable with
-rdoesn’t guarantee that opening the file will succeed — the file could be deleted or change permissions after your check. - Don’t confuse
-r $filenamewithopen my $fh, "<", $filename— the latter attempts to open the file, which *may* fail for reasons other than permissions.
Runnable Perl example
use strict;
use warnings;
# Take filename from command line or default
my $filename = shift || 'example.txt';
if (-e $filename) {
if (-r $filename) {
print "File '$filename' exists and is readable.\n";
} else {
print "File '$filename' exists but is NOT readable.\n";
}
} else {
print "File '$filename' does not exist.\n";
}
To test this script, run it with an existing file name or a non-existent one, for example:
perl -e '...' myfile.txt
This script first checks the file exists with -e, then tests readability with -r.
Summary
Use the Perl file test operator -r for a simple, idiomatic way to check if a file is readable. This is concise, fast, and respects underlying OS permissions. However, remember that permissions can change at any time, so attempting to open the file inside an eval or error-handling block is the most robust approach.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 4ms
Cannot read
(empty)Was this helpful?
Related Questions
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?