#!/usr/bin/perl use strict; use warnings; my @buffer; my $buffer_size = 10; my $match = qr/toolerror/; # Read a file from STDIN. while ( my $line = <> ) { if ( $line =~ /$match/ ) { # Discard the buffered lines. @buffer = (); # Print the matched line. print $line; } else { # Store non matching lines in a buffer. push @buffer, $line; # Maintain the buffer at a max size. if ( @buffer > $buffer_size ) { print shift @buffer; } } } # Print any remaining buffered lines. print @buffer; __END__