#!/usr/bin/perl use strict; use warnings; # We don't really need an array for one line, but it seems # conceptually nicer (and generalises more easily) my $max_buffer_size = 1; my @buffer; my $line; while ($line = ) { push @buffer, $line; # Replace the pattern match with your criterion if this # isn't right. @buffer = () if $line =~ /^.id/; if (scalar @buffer > $max_buffer_size) { print shift @buffer; } } print @buffer;