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

iibxawm4  于 12个月前  发布在  Perl
关注(0)|答案(3)|浏览(138)

我有一段代码,它打开一个文件并解析它。这个文本文档有一个冗余的结构,有多个条目。我需要在我的循环中提前查看是否有一个新条目,如果有,我将能够解析我的程序提取的所有数据。让我先展示一下我到目前为止的实现

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
}
ct3nt3jp

ct3nt3jp1#

尝试自己处理迭代:

my $line = <$fileHandler>;
while(1) { # keep looping until I say so
    my $nextLine = <$fileHandler>;

    if ($line =~ m/>/ || !defined $nextLine) {
        ### Do the stuff
    }
    ### Do any other stuff;

    last unless defined $nextLine;
    $line = $nextLine;
}

我在if语句中添加了额外的检查,假设您也希望在到达文件末尾时处理您拥有的内容。
或者,正如friedo所建议的,如果文件可以放入内存,你可以一次将整个文件加载到数组中:

my @lines = <$fileHandler>;
for (my $i = 0; $i <= $#lines; $i++) {
    if ($i == $#lines || $lines[$i+1] =~ />/) {
        ### Do the stuff
    }
}

这是更灵活的,因为你可以访问文件的任意行,以任何顺序,但如前所述,文件必须足够小,以适应内存。

64jmpszr

64jmpszr2#

处理这些问题的一个好方法是使用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
idv4meu8

idv4meu83#

我只是在#5中使用了Tie::File代码,这是非常公平的。我的in文件中有一个主机名,下一行是主机名或主机的crit级别。如果有crit级别,我就用主机名和crit来输出到CSV;如果没有crit分配,我就分配它0。
(我必须拆分行,因为该行是name:servername或critlevel:99,沿着清理前导/尾随空格)

for my $linenumber (0..$#file) {
        #print "$file[$linenumber]\n";
        if ($file[$linenumber] =~/name/) {
                ($crap,$server) = split(/\:/,$file[$linenumber],2);
                $server =~ s/^\s+|\s+$//g; 
                #print "$server\n";
                if ($file[$linenumber+1] =~/server/ && $linenumber <=$#file) { 
                        ($crap,$crit) = split(/\:/,$file[$linenumber+1],2);
                        $crit =~ s/^\s+|\s+$//g;
                        #print "$crit\n";
                }
                else { $crit = "0"; }
        $outstr = "$server,$crit\n";
        print $outstr;
        print OUTFILE $outstr;
        
        }
}

相关问题