What's the best way to open and read a file in Perl?
There are no universal standards, but there are reasons to prefer one or another. My preferred form is this:
open( my $input_fh, "<", $input_file ) || die "Can't open $input_file: $!";
The reasons are:
- You report errors immediately. (Replace "die" with "warn" if that's what you want.)
- Your filehandle is now reference-counted, so once you're not using it it will be automatically closed. If you use the global name INPUT_FILEHANDLE, then you have to close the file manually or it will stay open until the program exits.
- The read-mode indicator "<" is separated from the $input_file, increasing readability.
The following is great if the file is small and you know you want all lines:
my @lines = <$input_fh>;
You can even do this, if you need to process all lines as a single string:
my $text = join('', <$input_fh>);
For long files you will want to iterate over lines with while, or use read.
If you want the entire file as a single string, there's no need to iterate through it.
use strict;
use warnings;
use Carp;
use English qw( -no_match_vars );
my $data = q{};
{
local $RS = undef; # This makes it just read the whole thing,
my $fh;
croak "Can't open $input_file: $!\n" if not open $fh, '<', $input_file;
$data = <$fh>;
croak 'Some Error During Close :/ ' if not close $fh;
}
The above satisfies perlcritic --brutal
, which is a good way to test for 'best practices' :). $input_file
is still undefined here, but the rest is kosher.
Having to write 'or die' everywhere drives me nuts. My preferred way to open a file looks like this:
use autodie;
open(my $image_fh, '<', $filename);
While that's very little typing, there are a lot of important things to note which are going on:
We're using the autodie pragma, which means that all of Perl's built-ins will throw an exception if something goes wrong. It eliminates the need for writing
or die ...
in your code, it produces friendly, human-readable error messages, and has lexical scope. It's available from the CPAN.We're using the three-argument version of open. It means that even if we have a funny filename containing characters such as
<
,>
or|
, Perl will still do the right thing. In my Perl Security tutorial at OSCON I showed a number of ways to get 2-argumentopen
to misbehave. The notes for this tutorial are available for free download from Perl Training Australia.We're using a scalar file handle. This means that we're not going to be coincidently closing someone else's file handle of the same name, which can happen if we use package file handles. It also means
strict
can spot typos, and that our file handle will be cleaned up automatically if it goes out of scope.We're using a meaningful file handle. In this case it looks like we're going to write to an image.
The file handle ends with
_fh
. If we see us using it like a regular scalar, then we know that it's probably a mistake.