On Friday, 31 July 2015 19:51:07 UTC+5:30, John Black wrote:
[snip]
> >
> > open my $file, '<', 'test.txt' or die $!;
>
> I have a lot of old scripts that use the open(FILE,"< test.txt") form. Briefly, what is the
> drawback to that syntax? Is it worthwhile going back and changing them if people are still
> using the scripts? Thanks.
>
> John Black
>
> open(FILE,"< test.txt") form
This would make perl open the file "test.txt" for you, i.e., the leading space
is dropped.
With the 2-argument form of open you would have a hard time opening
a file actually named " test.txt", i.e., one with a leading a space.
Not so with the 3-arg form of open, though,
open FILE, "<", " test.txt" ...
Say, your file is named >test.txt , with the 2-arg form of open
it can be potentially overwritten if one is not careful.
my $fn = $ARGV[0]; #user enters ">test.txt"
open(FILE, $fn) ...
Lo & behold the file ">test.txt" will be nulled in the process of being read :-\
So, we see that based on the input filenames , open 2-arg is not reliable.
What's more, the 3-arg form is visually very appealing. The purpose and argument
stand out clearly, whatever be the filenames.
This is part of the problem. The other half of the pbm. comes from the 1st arg.
to open, the filehandle. (FILE in this case) Notice that a FILE is a "bareword".
A subroutine is also one. So if an unsuspecting user/maintainer were to add
a subroutine named FILE then things can get topsy turvy, & insidious, if it
happens to return a filehandle which happens to be used in your code.
Since filehandles are typically global (unless localized), they are open to
modifs. A subroutine might open FILE in it's scope & the coder closes it as
well in the subroutine. That action closes YOUR FILE filehandle as well.
Ofc, this can be avoided by localizing FILE within the sub.
Global filehandles of the *FILE variety suffer from file locking problems.
Say we open & then lock a file , but then either forget to close it or our
script gets aborted midway, but the files stays locked, thereby keeping all
potential users in a hanging mode.
Lexical FHs of the my $FILE variety are immune from such vagaries, as they
automagically close when the lexical goes out of scope.
So looking at all these problems, if you get the chance for a re-work on the
code, then upgrade all 2-arg opens to 3-arg forms.
More info can be seen here:
"Two-arg open() considered dangerous" on the hyperlink..
http://www.perlmonks.org/index.pl?node_id=131085