IO::File - 提供檔案句柄的物件方法
use IO::File;
my $fh = IO::File->new();
if ($fh->open("< file")) {
print <$fh>;
$fh->close;
}
my $fh = IO::File->new("> file");
if (defined $fh) {
print $fh "bar\n";
$fh->close;
}
my $fh = IO::File->new("file", "r");
if (defined $fh) {
print <$fh>;
undef $fh; # automatically closes the file
}
my $fh = IO::File->new("file", O_WRONLY|O_APPEND);
if (defined $fh) {
print $fh "corge\n";
my $pos = $fh->getpos;
$fh->setpos($pos);
undef $fh; # automatically closes the file
}
autoflush STDOUT 1;
IO::File
繼承自 IO::Handle
和 IO::Seekable
。它使用特定於檔案句柄的方法來延伸這些類別。
建立一個 IO::File
。如果它接收任何參數,它們會傳遞給 open
方法;如果開啟失敗,物件會被銷毀。否則,它會傳回給呼叫者。
建立一個 IO::File
,在一個新建立的暫時檔案上開啟讀寫。在可以這樣做的系統上,暫時檔案是匿名的(也就是說,它在建立後會取消連結,但會保持開啟)。如果無法建立或開啟暫時檔案,IO::File
物件會被銷毀。否則,它會傳回給呼叫者。
open
接受一個、兩個或三個參數。如果只有一個參數,它只是內建 open
函式的前端。如果使用兩個或三個參數,第一個參數是可能包含空白或其他特殊字元的檔名,第二個參數是開啟模式,後面可選擇性地接續一個檔案權限值。
如果 IO::File::open
接收到 Perl 模式字串(「>」、「+<」等)或 ANSI C fopen() 模式字串(「w」、「r+」等),它會使用基本的 Perl open
運算子(但會保護任何特殊字元)。
如果 IO::File::open
接收到一個數字模式,它會將該模式和選擇性的權限值傳遞給 Perl sysopen
運算子。權限預設為 0666。
如果 IO::File::open
接收到一個包含 :
字元的模式,它會將所有三個參數傳遞給三個參數的 open
運算子。
為了方便,如果 Fcntl 模組可用,IO::File
會匯出 O_XXX 常數。
binmode
在底層 IO
物件上設定 binmode
,如 perldoc -f binmode
中所述。
binmode
接受一個選擇性的參數,也就是要傳遞給 binmode
呼叫的層級。
有些作業系統可能會在目錄上執行 IO::File::new()
或 IO::File::open()
而不會產生錯誤。這種行為無法移植,也不建議使用。建議改用 opendir()
和 readdir()
或 IO::Dir
。
perlfunc、perlop 中的「I/O 運算子」、IO::Handle、IO::Seekable、IO::Dir
衍生自 Graham Barr <gbarr@pobox.com> 的 FileHandle.pm。