I use this syntax to open my files, since I learned that some years ago in a training and the books I have do it the same way.
open( INPUTFILE, "< $input_file" ) || die "Can't open $input_file: $!";
Some days ago i saw in a SO answer this form:
open( $input_file, "<", $input_file ) || die "Can't open $input_file: $!";
Is this format new or just doing the same, a different way, using a normal variable as filehandle?
Should I change to the "new" format? Does it have some advantages, or does the "old" format have some disadvantages?
You should use the three-argument version because it protects against files with crazy names. Consider the following:
my $file = "<file.txt";
open( INPUTFILE, "< $file" ) or die "$!";
This will interpolate as:
open( INPUTFILE, "< <file.txt" ) or die "$!";
...meaning you'll actually open a file named file.txt
instead of one named <file.txt
.
Now, for the filehandle, you want to use a lexical filehandle:
open( my $fh, "<", $file.txt ) or die "$!";
The reason for this is when $fh
goes out of scope, the file closes. Further, the other type of filehandle (I can't remember what it's called) has global scope. Programmers aren't all that imaginative, so it's likely that you'll name your filehandle INPUTFILE
or FH
or FILEHANDLE
. What happens if someone else has done the same, named their filehandle INPUTFILE
, in a module you use? Well, they're both valid and one clobbers the other. Which one clobbers? Who knows. It's up to the ordering of when they're opened. And closing? And what happens if the other programmer has opened INPUTFILE
but actually opened it for write? Worlds end, my friend, worlds end.
If you use a lexical filehandle (the $fh
) you don't have to worry about worlds ending, because even if the other programmer does call it $fh
, variable scope protects you from clobbering.
So yes, always use the three-argument form of open()
with lexical filehandles. Save the world.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With