in reply to edge case in substitution?

Where you have s{$tag=(.*?)\&}, just make it s{$tag=(.*?)(?:\&|$)}. So you match an ampersand or the end of string. Another way: s{$tag=([^&]*?)} should work

Caution: Contents may have been coded under pressure.