0

而不是我习惯的典型文件句柄:

open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;

如何检索指向文件中行的指针,以便可以在 wiil 中推进这些指针?我正在尝试创建两个指向其相应排序文件的指针,以便我可以根据一个文件中的行是“小于”还是“大于”另一个文件中的行来推进指针。

注意:假设输入文件很大。

4

3 回答 3

7

如果我理解正确,

perldoc -f tell

请注意,您要在读取一行之前tell获取该行的开始位置。

返回给定位置的函数是seek

或者,Tie::File可以让您将文件视为行数组,并在幕后进行一些巧妙的管理。

于 2011-01-18T18:14:47.940 回答
0

鉴于我的评论的答案,那么您需要将您的逻辑修改为(伪代码):

open Master;
open Transaction;

# Get initial records?
read first Master;
read first Transaction;

BATCH_LOOP:
while (!eof(Master) && !eof(Transaction))
{
     while (Master.ID < Transaction.ID && !eof(Master))
     {
           write Master;
           read next Master;
     }
     if (Master.ID > Transaction.ID)
     {
           report Missing Master for Transaction;
           read next Transaction;
           next BATCH_LOOP;
     }
     # Master.ID == Transaction.ID
     Update Master from Transaction;
     read next Transaction;
}

# At most one of the following two loop bodies is executed
while (!eof(Master))
{
     read next Master;
     write Master;
}

while (!eof(Transaction))
{
     Report Missing Master;
     read next Transaction;
}

双重(和三重)检查逻辑 - 它是在分散注意力的情况下即时编写的。但它接近你所需要的。

使用词法文件句柄:

open my $master, "<", $master_file or die "Failed to open master file $master_file ($!)";
open my $trans,  "<", $trans_file  or die "Failed to open transaction file $trans_file ($!)";

您可以相互独立地阅读它们。

于 2011-01-18T21:10:51.133 回答
0

为什么不存储在数组中?

my @lines1 = <INPUT1>;
my @lines2 = <INPUT2>;

这是 ysth 的 seek/tell 建议的示例,如果文件太大,这可能是您想要的更多: http ://www.nntp.perl.org/group/perl.beginners/2007/12/msg97522.html

于 2011-01-18T18:15:17.223 回答