構文 |
|
read ファイル・ハンドル,読み込みデータ格納場所,読み込みデータ数,オフセット read ファイル・ハンドル,読み込みデータ格納場所,読み込みデータ数 |
返り値 |
|
実際に読み込んだデータ数 |
説明
- ファイル・ハンドルからデータを読み込んで指定した場所に格納します。読み込みデータ数はバイト数ではなく文字数です。
- 実際に読み込んだデータ数を返します。ファイルの最後で関数を呼び出した場合は0を返します。読み取りエラーが発生した場合は未定義値を返します。
- オフセットを指定するとデータを格納する際に指定した分だけ後ろにズラして格納します。オフセットを省略した場合は先頭からデータを格納します。
使用例
#!/usr/bin/perl
use strict;
use warnings;
my $file = "data.txt";
open my $fh, '<', $file or die "$file:$!";
while (1) {
# Latin-1で100文字(=100バイト)ずつ読み込む
my $len = read $fh, my($buf), 100;
unless (defined $len) {
# 読み取り失敗
die "read error: $!";
} elsif ($len == 0) {
# 読み取り終了
last;
}
print "[$buf]\n";
}
close $fh;
#!/usr/bin/perl
use strict;
use warnings;
my $file = "data.txt";
# UTF-8で入力
open my $fh, '<:utf8', $file or die "$file:$!";
binmode STDOUT, ":utf8";
while (1) {
# UTF-8で100文字ずつ読み込む
my $len = read $fh, my($buf), 100;
unless (defined $len) {
# 読み取り失敗
die "read error: $!";
} elsif ($len == 0) {
# 読み取り終了
last;
}
print "[$buf]\n";
}
close $fh;