in reply to Search and replace next line

while (<>) { print; if (m/TheLineBefore/){ # read the line to be replaced my $line = <>; # do something with it $line =~ s/1/0/; # print the new version print $line; } } __DATA__ test data more TheLineBefore LocalCompilerPresent=1 more stuff
This is a frequent question, see also the search results for next line.

Replies are listed 'Best First'.
Re^2: Search and replace next line
by Anonymous Monk on Jan 05, 2005 at 10:16 UTC

    Won't solve the problem.

    • the OP asked to replace the instance(s) of LocalCompilerPresent=1 after the first one.
      Your script will only work if the wanted line is in the line immediately following the searched one. If there is a blank line in between, it will fail.
    • Your script will print both the original and replaced lines.
      I replace the line following the searched line. blank or not. Thats what I understand from the question.
      And the script does NOT print both lines. Read the source again.

      UPDATE: For some reason I answered to the wrong Node! Please Ignore. Sorry to the anon monk.
      Boris
      Your script will only work if the wanted line is in the line immediately following the searched one.

      True. But I understood him as wanting to replace the immediately following line.

      Your script will print both the original and replaced lines.

      Really? What does it output for you? For me, it says

      test data more TheLineBefore LocalCompilerPresent=0 more stuff
      which I take to be correct. No?