while ($line = ) { push @storage, $line); if ($line =~ /$string_to_find/i) { $counter=10; } if (@counter-- and @storage>=5) { print shift @storage; } }