Perl replace multiple strings simultaneously

后端 未结 2 1907
夕颜
夕颜 2020-12-17 17:23

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 a

2条回答
  •  执念已碎
    2020-12-17 18:00

    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".

提交回复
热议问题