Is there a way to check if a file is already open in Perl?
I want to have a read file access, so don't require flock
.
open(FH, "<$fileName") or die "$!\n" if (<FILE_IS_NOT_ALREADY_OPEN>);
# or something like
close(FH) if (<FILE_IS_OPEN>);
Is there a way to check if a file is already open in Perl?
I want to have a read file access, so don't require flock
.
open(FH, "<$fileName") or die "$!\n" if (<FILE_IS_NOT_ALREADY_OPEN>);
# or something like
close(FH) if (<FILE_IS_OPEN>);
Try:
if(tell(FH) != -1)
tell
reports where in the file you are. If you get back -1, an invalid position, you aren't anywhere in the file.
Why would you want to do that? The only reason I can think of is when you're using old style package filehandles (which you seem to be doing) and want to prevent accidentally saving one handle over another.
That issue can be resolved by using new style indirect filehandles.
open my $fh, '<', $filename or die "Couldn't open $filename: $!";
Perl provides the fileno function for exactly this purpose.
EDIT I stand corrected on the purpose of fileno()
. I do prefer the shorter test
fileno FILEHANDLE
over
tell FH != -1
Why do you care if it is already open? Are you trying to catch simultaneous reads?
You don't really need to care about closing the file. Either it's not open and the close fails because it has nothing to close, or the file is open and the close releases it. Either way, the file is not open on that filehandle. Just close the filehandle without caring it if is not open. Are you seeing something weird there?
Tell produces a warning (so does stat, -s, -e, etc..) with use warnings
(-w)
perl -wle '
open my $fh, "<", "notexists.txt";
print "can stat fh" if tell $fh
'
tell() on closed filehandle $fh at -e line 1.
-1
The alternatives fileno($fh)
and eof($fh)
do not produce warnings.
I found the best alternative was to save the output from open
.