in reply to Why a regexp won't increment the value of a variable

Looks like you're modifying @template on the first iteration (remember that $_ in the foreach loop is an alias), so the replacement string is no longer found in the subsequent iterations...