Multiple substitutions with a single regular expression in perl

后端 未结 3 1098
心在旅途
心在旅途 2021-01-24 01:44

Say I have the following in perl:

my $string;
$string =~ s/ /\\\\ /g;
$string =~ s/\'/\\\\\'/g;
$string =~ s/`/\\\\`/g;

Can the above substitut

3条回答
  •  萌比男神i
    2021-01-24 02:19

    Separate substitutions may be much more efficient than a single complex one (e.g. when working with fixed substrings). In such cases you can make the code shorter, like this:

    my $string;    
    for ($string) {
        s/ /\\ /g;
        s/'/\\'/g;
        s/`/\\`/g;
    }
    

提交回复
热议问题