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