OUT: while(<>) { next unless /keyword2/; while(<>) { last OUT if /keyword4/; process_line($_); } }