in reply to Getting next line after matched one

The basic technique is to read each line from the file, maintaining a flag called something like lastmatched. If lastmatched is set, print the current line. If the current line matches the pattern, set the lastmatched flag; otherwise clear it.

Replies are listed 'Best First'.
Re^2: Getting next line after matched one
by ramthen (Sexton) on Dec 30, 2004 at 20:53 UTC

    my question was : once a line is matched, what should I do , like increment pointer to go to next line to get that line in file ?

    I think previous two posts were talking about setting flags if match is found !

      The previous posts do go to the next line, the flag is set so that when you get to the next line, you know that the previous line was a match. If you get to a line, and the flag is set, then do whatever it is that you wanted to do after finding the matching line.
      UPDATE-
      I'm going to use tremmel's code to make sure that you understand what is going on, forgive me if I go in to too much detail, but I don't know where your level of understanding is - not trying to talk down to you, I'm a relative beginner myself.
      my $flag = 0; while (<FILE>) { #If not at end of file process next line if ($flag) { #flag is set, previous line was a match $flag = 0; #reset the flag do_something($_); #do what you want to do after finding match } if (/pattern/) { #if this line matches $flag = 1; #set the flag so I can do something on next line next; #go to next line, not required but might make more read +able } }
      Basically, whenever you evaluate <FOO> in scalar context, it reads the next line from the file handle FOO and returns it, or returns undef if you're at the end of the file. A normal
      while (<FOO>){
      loop is short for
      while (defined($_ = <FOO>)){
      So all you have to do to read the next line is execute <FOO> again, either by doing so directly and using the result, or by waiting for the next iteration of the loop (which will read it for you) and then dealing with it then (the flag, then, lets you know that last time you saw what you needed). Which is preferable depends on what else you need to do with what lines in the file.
      The problem with the approach you describe is that it won't work if two lines in a row match. For example, say you have a file like:
      foo
      bar
      barbar
      bell
      
      and the pattern is /bar/. bar will match; if you read in the next line and print it out, you won't notice that barbar also matches, and so won't print out bell. You could add some code to fix this, but the flag approach handles it quite nicely.