Main Content

File open and read in Perl - modernisation

Archive - Originally posted on "The Horse's Mouth" - 2010-06-19 06:59:35 - Graham Ellis

Some updates on file opening and reading in Perl ...

1. The original open function was good, but technically questionable in that the second parameter includes (as a single string) both the name of the file and an indicator as to whether it's being opened for read or write. The newer (three parameter form) of open, in which the read / write indicator has been separated out and the file name moved to a third parameter has been around a while now - and is recommended unless you're required to support very old Perl versions.

2. The <> operator - surrounding a file handle - has always been an interesting one to explain during courses, as it's so different to a more traditional function call. The readline function is a more conventional alternative these days - although you are required to pass in the file handle as a "typeglob" to it. Me thinks that's one difficult explanation removed, but perhaps another added in!

So
  open (FH,$filename) or die ("$! - $filename\n");
or
  open (FH,"<$filename") or die ("$! - $filename\n");
is replacable / improved by
  open (FH,"<",$filename) or die ("$! - $filename\n");

And
  while ($line = <FH>) {
may be replaced by
  while ($line = readline(*FH)) {
(but I am not claiming that as a universal improvement)

See full source [here]. And see [here] for a discussion of how / when you should move forward to using some of these newer features of Perl.