my @history = ("\n") x 3; while (<>) { print @history if /pattern/; push @history, $_; shift @history; }