my @previous; while () { if ($_ eq "STRING TO COMPARE WITH\n") { print $previous[0]; last; } push @previous, $_; shift @previous if @previous > 5; }