Perl的同时替换多个字符串

Perl的同时替换多个字符串

问题描述:

有没有办法在一个字符串替换多个字符串?
例如,我有字符串的Hello World一个多么可爱的一天,我想替换什么可爱用别的东西。

Is there any way to replace multiple strings in a string? For example, I have the string hello world what a lovely day and I want to replace what and lovely with something else..

$sentence = "hello world what a lovely day";
@list = ("what", "lovely"); # strings to replace
@replist = ("its", "bad"); # strings to replace with
($val = $sentence) =~ "tr/@list/@replist/d";
print "$val\n"; # should print "hello world its a bad day"..

任何为什么它不工作的想法?

Any ideas why it's not working?

感谢。

首先, TR 不工作的方式;咨询的perldoc perlop中有关详细信息,但 TR 确实音译,距离替代很大的不同。

First of all, tr doesn't work that way; consult perldoc perlop for details, but tr does transliteration, and is very different from substitution.

为此,要更换一个更正确的方法是

For this purpose, a more correct way to replace would be

# $val
$val =~ s/what/its/g;
$val =~ s/lovely/bad/g;

需要注意的是同时的变化是比较困难的,但我们可以做到这一点,例如,

Note that "simultaneous" change is rather more difficult, but we could do it, for example,

%replacements = ("what" => "its", "lovely" => "bad");
($val = $sentence) =~ s/(@{[join "|", keys %replacements]})/$replacements{$1}/g;

(逃逸可能有必要元字符替换过程的字符串。)

(Escaping may be necessary to replace strings with metacharacters, of course.)

这是目前仍只在任期的非常宽松感的同时,但确实,在大多数情况下,充当如果替换是在一个通完成。

This is still only simultaneous in a very loose sense of the term, but it does, for most purposes, act as if the substitutions are done in one pass.

此外,它是更正确的替换是什么,它的,而不是

Also, it is more correct to replace "what" with "it's", rather than "its".