Here is an option on how to do this, which is almost identical to your code with a slight difference.
use strict; use warnings; sub TemplateReplace { my($regex, $replacement, $text) = @_; $$text =~ s/($regex)/$replacement/gs; } my $text = "This is a test."; TemplateReplace("test", "banana", \$text); print $text;
This behavior is explicit, not implied. In practice, it works identically to Chas. Owens , but uses scalar refs instead of relying on an understanding of array behavior.
This will become more apparent to anyone reading your code that the TemplateReplace function intentionally modifies $ text.
In addition, he will tell you that you are using it incorrectly, cursing:
Can't use string ("This is a test.") As a SCALAR ref while "strict refs" in use at replace.pl line 9.
If you accidentally forgot \ somewhere.
source share