use strict; use warnings; sub substitute { my ($string, $from, $to) = @_; $from = qr/$from/ unless ref $from and ref $from eq 'Regexp'; my @a = $string =~ $from; $to =~ s/\$(\d+)/$a[$1-1]/g; # was $to =~ s/\$(\d+)/\Q$a[$1-1]/g; $string =~ s/$from/$to/; $string; } my @tests = ( [ "this is some test", "(is) s(o)me", '$1 n$2t a' ], [ "this is some test", "is some", 'is not a' ], ); for my $t (@tests) { print "[$t->[0]]..."; print "[",substitute(@$t), "]\n"; } #### [this is some test]...[this is not a test] [this is some test]...[this is not a test]