Main Content

Perl - its up to YOU to check your file opened

Archive - Originally posted on "The Horse's Mouth" - 2006-02-23 00:53:52 - Graham Ellis

When you open a file in Perl, you should ALWAYS check the return status to see if your open function worked. If it can't open the file you've requested it won't print out an error - the failure is silent unless you check for it.

Thus:

open (FH,"abc.txt") or die ("Cannot open abc.txt\n");
Perl will fail to open a file for read if the file does not exist, or if the file is not readable by the user requesting it

open (FH,">abc.txt") or die ("Cannot open abc.txt\n");
Perl will fail to open a file for write if the user running the Perl program does not have appropiate write permissions. A file can be opened for write whether or not it already exists; if it does exist the open statement shown will cause the existing content to be deleted.