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>);
The Scalar::Util module provides the
openhandle()
function for this. Unlike fileno(), it handles perl filehandles which aren't associated with OS filehandles. Unlike tell(), it doesn't produce warnings when used on an unopened filehandle From the module's documentation: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.
Tell produces a warning (so does stat, -s, -e, etc..) with
use warnings
(-w)The alternatives
fileno($fh)
andeof($fh)
do not produce warnings. I found the best alternative was to save the output fromopen
.Please see the answer regarding
openhandle()
fromScalar::Util
. The answer I originally wrote here was once the best we could do, but it's now badly outdated.Perl provides the fileno function for exactly this purpose.
EDIT I stand corrected on the purpose of
fileno()
. I do prefer the shorter testfileno FILEHANDLE
over
tell FH != -1