my ($buf, $onelineback, $twolinesback, $thisline); while($buf = ) { if ($buf =~ /somestring/) { if defined($twolinesback) { print $twolinesback; } else { print "Matched, but not enough lines read yet\n"; } } $twolinesback = $onelineback; $onelineback = $thisline; $thisline = $buf; }