Search code examples
perlfilehandle

Perl read subsection inside open file handle


I have open a file using:

open (FH, "<".$File::Find::name) or die "cannot open file \"".$File::Find::name." \"!";
while (<FH>) {
  ...my code...  
}

I parse the lines using Regular expressions to get the data I want. Now I want to read a subsection of a file until I see the ending of that subsection inside my while-loop. i.e: reading from "StartSection" until "EndSection" line by line:

open (FH, "<".$File::Find::name) or die "cannot open file 
\"".$File::Find::name." \"!";
while (<FH>) {
  ...my code...
  if (/^StartSection$/) {
    while (<FH> !~ /^EndSection) {
      ... more code....
    }
  }
}

How must I program this correctly in Perl?


Solution

  • I can think of several ways to answer this question, but I'll go with the flip-flop operator answer:

    while (<FH>) {
       if (/^StartSection$/ .. /^EndSection/) {
           ... special code ...
       } else {
           ... regular code ...
       }
    }