/e treats the contents of the replace operand of the s/// operator as Perl source code. Therefore, $replace (not its content) is treated as source code. An expression consisting of a variable name returns its contents, so s/.../$replace/e replaces the match with the contents of $replace.
To execute Perl code in a variable, you need eval EXPR. Change
The latter can also be written as
(note the double "e") but I find that to be rather obfuscated. eval EXPR is dangerous so it shouldn't be hidden.
Update: Added missing code to add quotes to the code to execute.