views:

4562

answers:

5

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>);
+17  A: 

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.

chaos
It works, Thanks :)
+6  A: 

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: $!";
Leon Timmermans
Oh great, good to know. Thanks.
matt: try Perl::Critic for better style
Alexandr Ciornii
+2  A: 

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

converter42
Well... not really. It provides fileno for the purpose of getting the system file descriptor number. Determining whether the filehandle is open is a side effect (just as it's a side effect of tell).
chaos
And not a completely reliable side-effect either. It's possible to have a filehandle that's open to something other than a filedescriptor, in which case `fileno` sensibly returns undef. Examples are tied handles and handles opened to scalars.
hobbs
+1  A: 

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?

brian d foy
A: 

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.

CoffeeMonster