# replace($string, \@from, \@to, $allow_recursion) # recursion is turned off by default sub replace { my ($str, $from, $to, $recurse) = @_; # set up a hash for easy lookup my %replace; @replace{@$from} = @$to; # this is the safe way to create a regex # alternation of the possible "from" strings my $from_rx = join '|', map { quotemeta } sort { length($b) <=> length($a) } @$from; # compile the regex $from_rx = qr/($from_rx)/; # this handles non-recursion # as well as recursion... you # might consider this a hack do { $str =~ s/$from_rx/$replace{$1}/g or $recurse = 0; } while $recurse; return $str; }