如何查看Perl中文件的下一行

前端之家收集整理的这篇文章主要介绍了如何查看Perl中文件的下一行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一段代码打开一个文件并解析它.此文本文档具有冗余结构并具有多个条目.我需要在循环中查看是否有新条目,如果有,我将能够解析我的程序提取的所有数据.让我首先展示我到目前为止的实施情况

use strict;
my $doc = open(my $fileHandler,"<","test.txt");

while(my $line = <$fileHandler>) {
    ## right here I want to look at the next line to see if 
    ## $line =~ m/>/ where > denotes a new entry
}

解决方法

处理这些问题的一个好方法是使用 Tie::File,它允许您将文件视为数组,而不会将文件实际加载到内存中.它也是perl v5.7.3以来的核心模块.

use Tie::File;
tie my @file,'Tie::File',"test.txt" or die $!;

for my $linenr (0 .. $#file) {             # loop over line numbers
    if ($file[$linenr] =~ /foo/) {         # this is the current line
        if ($file[$linenr + 1] =~ /^>/ &&  # this is the next line
            $linenr <= $#file) {           # don't go past end of file
             # do stuff
        }
    }
}
untie @file;   # all done

猜你在找的Perl相关文章