It's certainly be helpful if you posted some code - see
How do I post a question effectively?. Do you have all your lines in an array? Do you have the whole file in a string? The solution depends strongly on these questions. Assuming you want to do it streaming, perhaps you mean something like:
while (defined (my $line = <$file>)) {
push @cache, $line;
shift @cache if @cache > 20;
print join "\n", @cache if $line =~ /test/;
}