Search for grep, the Unix command, implementation in Perl. There are at least one such implementations posted around here (don't have the (search) links handy); another was posted long ago in comp.lang.perl.misc newsgroup. Yet another is
App::Ack; refer to
&print_line_with_context &
&get_context subs.