【问题标题】:File handles in PerlPerl 中的文件句柄
【发布时间】:2011-01-18 18:08:47
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您确定需要倒退吗?难道你不只需要两个独立的手柄,这样你就可以推进每个吗?这听起来像是经典的事务处理代码(批处理风格);遍历排序的主文件,读取关联的事务记录,应用更改,写入新的主文件。或者像 comm 在 Perl 中重新实现。
  • 我不需要倒退,我希望我不是在暗示。事实上,您对问题的描述符合我提出问题的初衷。

标签: perl filehandle


【解决方案1】:

如果我理解正确的话,

perldoc -f tell

请注意,您希望tell 只是读取一行以获得该行的开始位置。

返回给定位置的函数是seek

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

【讨论】:

    【解决方案2】:

    为什么不存储在数组中?

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

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

    【讨论】:

    • 输入文件太大怎么办?
    • 然后使用 ysth 的解决方案,或者使用 $. 输入行号变量。
    【解决方案3】:

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

    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 ($!)";
    

    您可以相互独立阅读。

    【讨论】:

    • @tchrist:接下来到处都是 - 很棒的东西,p-code! DWIMmery 的终极...
    猜你喜欢
    • 1970-01-01
    • 2015-04-13
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2015-05-10
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多