Produces the output:use strict; use warnings; my %replace = qw( COM SEC MOC COM SEC COM CO MOC ); my $searchpat = join '|', sort { length $b <=> length $a } keys %repla +ce; $searchpat = qr/$searchpat/; # optional, dunno if it speeds up things my $example = "FOO CO COM BAR MOC SEC"; $example =~ s/($searchpat)/$replace{$1}/g; print "$example\n";
As you can see, it also handles circularity without problem; COM <-> SEC.FOO MOC SEC BAR COM COM
Note that I'm sorting the keys on length to make sure longer patterns match first (otherwise "COM" would become "SECM").
which prints:my $example = "MOC.COMPUTER.COM.FOO / SEC.SECT / CO"; $example =~ s/\b($searchpat)\b/$replace{$1}/g; print "$example\n";
COM.COMPUTER.SEC.FOO / COM.SECT / MOC
Note that in this case sorting on the length of the key is not necessary, so you can simply do my $searchpat = join '|', keys %replace;
In reply to Re: Ordering hash replacements to avoid clobbering things
by xmath
in thread Ordering hash replacements to avoid clobbering things (update chaining)
by grinder
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |