use strict; use warnings; my $test_data = 'This is some test data: $888...!'; my $pattern = qr{(\$?[0-9,]+)}; my $replacement = '$1<\/test>'; my $first_test = replace_with_constant($test_data, $pattern, $replacement); my $replacement_func = sub { "" . $1 . "<\/test>"; }; # OR my $replacement_func = sub { "$1<\/test>"; }; my $second_test = replace_with_dynamic($test_data, $pattern, $replacement_func); print $first_test, "\n", $second_test, "\n"; sub replace_with_constant { my ($data, $pat, $rep) = @_; $data =~ s/$pat/$rep/; # OR $data =~ s/$pat/$rep/e; return $data; } sub replace_with_dynamic { my ($data, $pat, $rep) = @_; $data =~ s/$pat/&$rep()/e; return $data; }