file-io beginner
How to check if a file exists and is readable in Perl
Question
What file test operators should I use to check file existence and permissions in Perl?
Perl provides file test operators for checking file properties before operations:
use strict;
use warnings;
my $filename = 'data.txt';
# Check if file exists
if (-e $filename) {
print "File exists\n";
}
# Check if file exists and is readable
if (-r $filename) {
print "File is readable\n";
}
# Check if file exists and is writable
if (-w $filename) {
print "File is writable\n";
}
# Check if it's a regular file (not directory)
if (-f $filename) {
print "Is a regular file\n";
}
# Check if it's a directory
if (-d $filename) {
print "Is a directory\n";
}
# Get file size
if (-s $filename) {
my $size = -s $filename;
print "File size: $size bytes\n";
}
# Combining tests (stacked operators)
if (-f $filename && -r $filename && -s $filename) {
print "File exists, is readable, and not empty\n";
}
# Common pattern
open my $fh, '<', $filename or die "Cannot open $filename: $!";
Common operators: -e (exists), -f (file), -d (directory), -r (readable), -w (writable), -x (executable), -s (size), -z (zero size).
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?