foreach $line (@lines) { if ($line =~m/^SY /) { $line =~s/^SY/CN/) if (next =~m/^SY /) { next =~s/^SY/ /; } } } # so if the first line starts 'SY' replace with 'CN', but if the next after the replacement does, then change SY on the next line for ' '.