Search code examples
perl

How to read line after finding a pattern?


I've got the lines

CHANNEL(SYSTEM.DEF.SVRCONN) CHLTYPE(SVRCONN)
id=3

What I want to do is to retrieve the id after I do a search on the file and found the first line.

open(CHECKFILE8, "$file");
while (<CHECKFILE8>) {             #while loop to loop through each line in the file
    chomp;                         #take out each line by line
    $datavalue = $_;               #store into var , $datavalue.
    $datavalue =~ s/^\s+//;        #Remove multiple spaces and change to 1 space from the front
    $datavalue =~ s/\s+$//;        #Remove multiple spaces and change to 1 space from the back
    $datavalue =~ s/[ \t]+/ /g;    #remove multiple "tabs" and replace with 1 space
    if ($datavalue eq "CHANNEL(SYSTEM.DEF.SVRCONN) CHLTYPE(SVRCONN)") {
        # HOW TO READ THE NEXT LINE?
    }
}

Solution

  • The same way you're reading all of the other lines: with the expression <CHECKFILE8>. For example:

    my $nextline = <CHECKFILE8>;
    

    You should be aware, though, that opening filehandles via a bareword identifier is somewhat archaic Perl. It's generally safer and more idiomatic to let Perl create filehandles in lexically scoped variables for you:

    open my $checkfile8, '<', $file or die "Can't open $file: $!";
    while (<$checkfile8>) { ... }
    

    You are using use strict, right?