13

IO::Fileオブジェクトまたはtypeglob(\*STDOUTまたはSymbol::symbol_to_ref("main::FH"))のいずれかが与えられます。それが読み取りハンドルか書き込みハンドルかをどのように判断しますか?この情報を渡すためにインターフェースを拡張することはできません(実際のクローズの前にclose呼び出しを追加するためにオーバーライドしていflushます)。sync

現在、私はファイルハンドルを試し、エラーを無視しようflushとしています(これは、ファイルハンドルを読み取ろうとしたときに得られるものです)。sync"Invalid argument"flushsync

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: $!";
        }
};
4

1 に答える 1

8

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 / Write
于 2009-03-23T05:43:23.310 に答える