while (...) { if (/xxyy/) # end of your block searched { $flag = 0; } if (/.../) { $flag = 1; } ... ... if ($flag == 1) { ... } }