如何确定 Perl 文件句柄是读句柄还是写句柄?
您将获得一个 IO::File
对象或 typeglob(\*STDOUT
或 Symbol::symbol_to_ref("main::FH")
); 您将如何确定它是读句柄还是写句柄? 无法扩展接口来传递此信息(我正在覆盖 close
以在实际关闭之前添加对 flush
和 sync
的调用)。
目前,我正在尝试刷新
和同步
文件句柄并忽略错误“无效参数”
(这是我尝试时得到的结果) code>flush
或 sync
读取文件句柄):
eval { $fh->flush; 1 } or do {
#this seems to exclude flushes on read handles
unless ($! =~ /Invalid argument/) {
croak "could not flush $fh: $!";
}
};
eval { $fh->sync; 1 } or do {
#this seems to exclude syncs on read handles
unless ($! =~ /Invalid argument/) {
croak "could not sync $fh: $!";
}
};
You are given either an IO::File
object or a typeglob (\*STDOUT
or Symbol::symbol_to_ref("main::FH")
); how would you go about determining if it is a read or write handle? The interface cannot be extended to pass this information (I am overriding close
to add calls to flush
and sync
before the actual close).
Currently I am attempting to flush
and sync
the filehandle and ignoring the error "Invalid argument"
(which is what I get when I attempt to flush
or sync
a read filehandle):
eval { $fh->flush; 1 } or do {
#this seems to exclude flushes on read handles
unless ($! =~ /Invalid argument/) {
croak "could not flush $fh: $!";
}
};
eval { $fh->sync; 1 } or do {
#this seems to exclude syncs on read handles
unless ($! =~ /Invalid argument/) {
croak "could not sync $fh: $!";
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看 fcntl 选项。 也许将
F_GETFL
与O_ACCMODE
结合使用。编辑:我在午餐时进行了一些谷歌搜索和玩,这里有一些可能不可移植代码,但它适用于我的 Linux 机器,可能还适用于任何 Posix 系统(甚至可能是西格温,谁知道呢?)。
输出示例:
Have a look at the fcntl options. Maybe
F_GETFL
withO_ACCMODE
.Edit: I did a little googling and playing over lunch and here is some probably non-portable code but it works for my Linux box, and probably any Posix system (perhaps even Cygwin, who knows?).
Example output: