while (defined (my $line = <$file>)) { push @cache, $line; shift @cache if @cache > 20; print join "\n", @cache if $line =~ /test/; }