open( IN, "some_file.tex" ) or die $!; { local $/ = "(STOP)\n"; my $expected_id = 1; while () { # read a whole block up to "(STOP)\n" if ( s/\(LABEL O $expected_id\)\n/$1 NEWSTUFF/ ) { print; # all done with this block } else { print "(LABEL O $expected_id)\n NEWSTUFF\n(STOP)\n"; # add a new block } my $expected_id++; } } # closing this block drops the local value of $/ # now $/ is back to it's default value (in case you # have to read other stuff in the normal fashion).