Perl 正则表达式从哈希替代 [英] Perl regex substitute from hash
问题描述
是否有一种有效的方法可以使用 Perl 哈希中的值替换一堆字符串?
Is there an efficient way to substitute a bunch a strings using values from a Perl hash?
例如
$regex{foo} = "bar";
$regex{hello} = "world";
$regex{python} = "perl";
open(F, "myfile.txt");
while (<F>) {
foreach $key (keys %regex) {
s/$key/$regex{$key}/g;
}
}
close(F);
有没有办法在 Perl 中完成上述操作?
Is there a way to accomplish the above in Perl?
推荐答案
第一个问题:你确定你拥有的东西低效吗?
First question: are you sure that what you have is inefficient?
其次,最明显的下一步是将所有内容合并到一个正则表达式中:
Second, the most obvious next step would be to pull everything into a single regex:
my $check = join '|', keys %regex;
然后你可以做如下替换:
And then you can do the substitution as:
s/($check)/$regex{$1}/g;
如果键有足够的重叠,正则表达式引擎必须不断地重新检查相同的字母,这仍然可能是缓慢的".您可以使用类似 Regexp::Optimizer 之类的东西来消除重叠.但是优化的成本可能不仅仅是做所有事情的成本,这取决于有多少更改(散列中的键/值)以及您修改了多少行.过早的优化——!
This can still be "slow" with sufficient overlap of the keys where the regex engine has to recheck the same letters constantly. You can possibly use something like Regexp::Optimizer to eliminate the overlap. But the cost of optimising may be more than the cost of just doing everything, depending on how many changes (key/values in your hash) and how many lines you're modifying. Premature optimisation-- !
请注意,当然,您的示例代码不会对替换后的文本执行任何操作.它不会就地修改文件,因此我假设您正在单独处理该文件.
Note that, of course, your example code isn't doing anything with the text after the substitution. It won't modify the file in-place, so I'm assuming you're handling that separately.
这篇关于Perl 正则表达式从哈希替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!