I have some subroutines that I call like this myWrite($fileName, \@data). myWrite() opens the file and writes out the data in some way. I want to modify myWrite so that I can call it as above or with a filehandle as the first argument. (The main reason for this modification is to delegate the opening of the file to the calling script rather than the module. If there is a better solution for how to tell an IO subroutine where to write, i’d be glad to hear it.)
In order to do this, I must test whether the first input var is a filehandle. I figured out how to do that by reading this question.
Now here’s my question: I also want to test whether I can write to this filehandle. I can’t figure out how to do that.
Here’s what I want to do:
sub myWrite {
my ($writeTo, $data) = @_;
my $fh;
if (isFilehandle($writeTo)) { # i can do this
die "you're an immoral person\n"
unless (canWriteTo($writeTo)); # but how do I do this?
$fh = $writeTo;
} else {
open $fh, ">", $writeTo;
}
...
}
All I need to know is if I can write to the filehandle, though it would be nice to see some general solution that tells you whether you’re filehandle was opened with “>>” or “<“, or if it isn’t open, etc.
(Note that this question is related but doesn’t seem to answer my question.)
Detecting Openness of Handles
As Axeman points out,
$handle->opened()tells you whether it is open.produces
As you see, you cannot use
Scalar::Util::openhandle(), because it is just too stupid and buggy.Open Handle Stress Test
The correct approach, if you were not using
IO::Handle->opened, is demonstrated in the following simple little trilingual script:Which when run produces:
That is how you test for open file handles!
But that wasn’t even your question, I believe.
Still, I felt it needed addressing, as there are too many incorrect solutions to that problem floating around here. People need to open their eyes to how these things actually work. Note that the two functions from
Symboluse thecaller’s package if necessary—which it certainly often is.Determining Read/Write Mode of Open Handle
This is the answer to your question:
Which, when run, produces this output:
Happy now, Schwern? ☺