最近策划非要搞一堆一样的脚本,然后其中的一些效果ID需要替换成别新的,
这样的ID总共有50多个,替换软件的话只能一个一个搞,还担心中间搞错了,比如,复制粘贴过程中,只复制了原ID,新的ID没有换,那就把原ID替换成了上一个要替换的新ID.
于是网上搜搜看一次性替换多个字符串的方法,这个方法如下:
#!/usr/bin/perl
use strict;
use warnings;
my %replace = (
quick => "slow",
lazy => "energetic",
);
my $regex = join "|", keys %replace;
$regex = qr/$regex/; # qr 创建正则表达式
my $s = "The quick brown fox jumps over the lazy dog";
$s =~ s/($regex)/$replace{$1}/g;
print "$s\n";
但是这个替换有一个缺陷
this approach will have problems if you'll ever want to have 2 replace strings that one of them is prefix of another (for example: "dep"=>1, "depesz" => 2). to avoid the problem you should sort the keys of %replace by descreasing length of key. – user80168
简单来讲就是两个key不能有子串关系,否则的话,需要人为的给sort一下keys让长串在前面