我有一段代码打开一个文件并解析它.此文本文档具有冗余结构并具有多个条目.我需要在循环中查看是否有新条目,如果有,我将能够解析我的程序提取的所有数据.让我首先展示我到目前为止的实施情况
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