in reply to Re^3: Question on File Handler and Subroutines in Perl
in thread Question on File Handler and Subroutines in Perl
better written as:open FILE, $file;
The three argument version of open where the open mode (read,write,append) is explicitly specified has some advantages. With just 2 arguments, if somehow $file was say ">somefile", the open would clobber the contents of "somefile". Specifically saying that this is an "open for the purpose of reading" prevents that. The die message, terminates the program with some printed reason, $! gives additional O/S info, perhaps "permission denied", "file does not exist" or something. In a more complex app, I try to explain to the user in terms that they understand what this file that failed to open is "configuration file", "Club Roster Spreadsheet" or whatever in addition to the actual file name. This can be very helpful for the user.open FILE, '<', $file or die "unable to open $file for reading $!";
Also it is possible to use a lexical variable for the file handle instead of a label like FILE which is global in scope.
In a small one pager, I often don't worry about this. However in longer programs this can be important- I would pass the lexical file handle to a subroutine rather than relying upon a global value. Also note that the lexical file handle will be closed if it goes out of scope.open my $config_fh , '<', $file or die "unable to open Configuration $ +file for reading $!";
As a final note: in the die message, if you end it with an explicit "\n", like "some message $!\n", that suppresses the Perl code line number from the message. I sometimes do that in programs written for absolute non-computer types as that extra info can confuse them and subtract from the main error message!
|
|---|