while (<$_>) { print OUT @history if /$pattern/; print OUT $_ if /$pattern/; # adds line with match push @history, $_; shift @history; }