$counter = 0; foreach(@newstuff){ $counter++; if(m/Ent/){ $counter=0;} if(m/Payor/){ if($counter > $hold){ $hold = $counter; } } } $counter2 = 0; foreach(@newstuff){ $counter2++; if(m/Ent/){ $counter2=0;} if(m/Payor/){ if($counter2 < $hold){ $temp = $counter2; for($temp;$temp < $hold; $temp++){ #for($j=0;$j < $hold; $j++){ s/Payor/\nPayor/; } } } }