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.

Leave a Comment