use strict; use warnings; my ( $prevLine, $nextLine ); for ( ; ; ) { last if eof DATA; chomp( my $currLine = defined $nextLine ? $nextLine : ); if ( $currLine =~ /match this/ ) { print '-' x 25, "\n"; chomp( $nextLine = ) if !eof DATA; print $prevLine, "\n" if defined $prevLine; print $currLine, "\n"; print $nextLine, "\n" if defined $nextLine; print '-' x 25, "\n"; } else { undef $nextLine; } $prevLine = $currLine; } __DATA__ The first line match this Not this abcdefg The one above Another match this 1 Another match this 2 the one below match this 2 zxcvbnn Another match this blank above Second to the last line The last line match this