Search code examples
perlparsingsearchpeek

How to look at the next line of a file in Perl


I have a piece of code which opens up a file and parses it. This text document has a redundant structure and has multiple entries. I need to peek ahead within my loop to see if there is a new entry, if there is, I will be able to parse all of the data my program extracts. Let me first show my implementation so far

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
}

Solution

  • A nice way to handle these problems is using Tie::File, which allows you to treat a file like an array, without the performance penalty of actually loading the file into memory. It is also a core module since 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