# assuming the file is already opened and has a filehandle my @temp; # and assuming that you won't match before the first 5 lines.. while (my $line = ) { push @temp, $line; shift @temp if (scalar @temp > 5); if ($line =~ /foo/) { # we've got a match. print $temp[0]; } }