my @history = ('') x 4; while (<>) { push @history, $_; shift @history; print @history, $_ if /pattern/; }