如何测试我是否可以写入文件句柄? [英] How can I test if I can write to a filehandle?
问题描述
我有一些像这样调用的子程序 myWrite($fileName, @data)
.myWrite()
打开文件并以某种方式写出数据.我想修改 myWrite
以便我可以像上面一样调用它或,并将文件句柄作为第一个参数.(这种修改的主要原因是将文件的打开委托给调用脚本而不是模块.如果有更好的解决方案来告诉 IO 子例程在哪里写,我很高兴听到它.)
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.
这是我想要做的:
sub myWrite {
my ($writeTo, $data) = @_;
my $fh;
if (isFilehandle($writeTo)) { # i can do this
die "you're an immoral person
"
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.)
推荐答案
仍在试验这个,但也许您可以尝试对文件句柄进行零字节系统写入并检查错误:
Still experimenting with this, but maybe you can try a zero-byte syswrite to a filehandle and check for errors:
open A, '<', '/some/file';
open B, '>', '/some/other-file';
{
local $! = 0;
my $n = syswrite A, "";
# result: $n is undef, $! is "Bad file descriptor"
}
{
local $! = 0;
my $n = syswrite B, "";
# result: $n is 0, $! is ""
}
fcntl
看起来也很有希望.您的里程可能会有所不同,但这样的事情可能走在正确的轨道上:
fcntl
looks promising too. Your mileage may vary, but something like this could be on the right track:
use Fcntl;
$flags = fcntl HANDLE, F_GETFL, 0; # "GET FLags"
if ( ($flags & O_ACCMODE) & (O_WRONLY|O_RDWR) ) {
print "HANDLE is writeable ...
"
}
这篇关于如何测试我是否可以写入文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!