Perl Language File I/O (reading and writing files) "use autodie" and you won't need to check file open/close failures


autodie allows you to work with files without having to explicitly check for open/close failures.

Since Perl 5.10.1, the autodie pragma has been available in core Perl. When used, Perl will automatically check for errors when opening and closing files.

Here is an example in which all of the lines of one file are read and then written to the end of a log file.

use 5.010;    # 5.010 and later enable "say", which prints arguments, then a newline
use strict;   # require declaring variables (avoid silent errors due to typos)
use warnings; # enable helpful syntax-related warnings
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding
use autodie;  # Automatically handle errors in opening and closing files

open(my $fh_in, '<', "input.txt"); # check for failure is automatic

# open a file for appending (i.e. using ">>")
open( my $fh_log, '>>', "output.log"); # check for failure is automatic

while (my $line = readline $fh_in) # also works: while (my $line = <$fh_in>)
     # remove newline
     chomp $line;

     # write to log file
     say $fh_log $line or die "failed to print '$line'"; # autodie doesn't check print

# Close the file handles (check for failure is automatic)
close $fh_in;
close $fh_log;

By the way, you should technically always check print statements. Many people don't, but perl (the Perl interpreter) doesn't do this automatically and neither does autodie.