in reply to Restarting counters in text

use strict; use warnings; $_ =<<SQ; <exm>This is example 1 <exm>This is example 2 <exm>This is example 3 <exm>This is example 4 SQ s/<exm>/'<exm num="'.++$_.'">'/eg; print;
or just take the line number from the string:
s/<exm>(?=.+?example\s+(\d+))/<exm num="$1">/g;