Perl File Handling

Reading and writing files in Perl

Opening Files

open(my $fh, '<', "file.txt") or die "Cannot open: $!"; # read
open(my $fh, '>', "file.txt") or die "$!"; # write (overwrite)
open(my $fh, '>>', "file.txt") or die "$!"; # append

Reading Files

my $line = <$fh>; # read one line
while (my $line = <$fh>) { # read line by line
    chomp($line); # remove newline
    print "$line\n";
}
my @lines = <$fh>; # read all lines into array

Writing Files

print $fh "Line of text\n"; # write to file
say $fh "Line of text"; # write with newline (requires use feature 'say')

Closing Files

close($fh) or die "Cannot close: $!"; # close file handle

File Tests

-e "file.txt" # file exists
-f "file.txt" # is regular file
-d "dir" # is directory
-r "file.txt" # readable
-w "file.txt" # writable
-s "file.txt" # file size