if performance is key, perhaps you could do this with grep command, the command line utility that is. It has an -A and -B option to print the required number of prematch and postmatch lines. and if you have more code than just this matching business, you could wrap the system or backticks call to grep from within a perl script, that does whatever it wants with the match and contextual lines.
the hardest line to type correctly is: stty erase ^H