您将获得一个IO::File对象或一个typeglob (\*STDOUT或Symbol::symbol_to_ref("main::FH"));您将如何确定它是一个读句柄还是写句柄?无法扩展该接口以传递此信息(我正在重写close,以便在实际关闭之前添加对flush和sync的调用)。
目前,我正在尝试对文件句柄执行flush和sync操作,而忽略错误"Invalid argument" (这是我试图对文件句柄执行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: $!";
}
};发布于 2009-03-23 05:43:23
看看fcntl选项。也许是F_GETFL和O_ACCMODE。
编辑:我在午餐时搜索了一下,玩了玩,这里有一些可能不可移植的代码,但它可以在我的Linux机器上运行,也可能在任何Posix系统上运行(也许甚至是Cygwin,谁知道呢?)。
use strict;
use Fcntl;
use IO::File;
my $file;
my %modes = ( 0 => 'Read only', 1 => 'Write only', 2 => 'Read / Write' );
sub open_type {
my $fh = shift;
my $mode = fcntl($fh, F_GETFL, 0);
print "File is: " . $modes{$mode & 3} . "\n";
}
print "out\n";
$file = new IO::File();
$file->open('> /tmp/out');
open_type($file);
print "\n";
print "in\n";
$file = new IO::File();
$file->open('< /etc/passwd');
open_type($file);
print "\n";
print "both\n";
$file = new IO::File();
$file->open('+< /tmp/out');
open_type($file);输出示例:
$ perl test.pl
out
File is: Write only
in
File is: Read only
both
File is: Read / Writehttps://stackoverflow.com/questions/672214
复制相似问题