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