该文件将不适合内存。它超过 100GB,我想按行号访问特定行。在我到达它之前,我不想逐行计算。
我已阅读http://docstore.mik.ua/orelly/perl/cookbook/ch08_09.htm
当我使用以下方法构建索引时,行返回工作到某个点。一旦行号非常大,返回的行是相同的。当我转到文件中的特定行时,将返回同一行。它似乎适用于第 1 行到第 350000 行(大约);
# usage: build_index(*DATA_HANDLE, *INDEX_HANDLE)
sub build_index {
my $data_file = shift;
my $index_file = shift;
my $offset = 0;
while (<$data_file>) {
print $index_file pack("N", $offset);
$offset = tell($data_file);
}
}
# usage: line_with_index(*DATA_HANDLE, *INDEX_HANDLE, $LINE_NUMBER)
# returns line or undef if LINE_NUMBER was out of range
sub line_with_index {
my $data_file = shift;
my $index_file = shift;
my $line_number = shift;
my $size; # size of an index entry
my $i_offset; # offset into the index of the entry
my $entry; # index entry
my $d_offset; # offset into the data file
$size = length(pack("N", 0));
$i_offset = $size * ($line_number-1);
seek($index_file, $i_offset, 0) or return;
read($index_file, $entry, $size);
$d_offset = unpack("N", $entry);
seek($data_file, $d_offset, 0);
return scalar(<$data_file>);
}
我也尝试过使用 DB_file 方法,但似乎需要很长时间才能打成平手。我也不太明白“DB_RECNO 访问方法将数组绑定到文件,每个数组元素一行”的含义。并没有把文件读入数组正确吗?