open (FH,"report");
read(FH,$text,-s "report");
$fill{"place"} = "Dhahran";
$fill{"wdesc:desc"} = "hot";
$fill{"dayno.days"} = 4;
$text =~ s/%(\w+)%/$fill{$1}/g;
print $text;
这是“报告”模板文件的内容
"I am giving a course this week in %place%. The weather is %wdesc:desc%
and we're now onto day no %dayno.days%. It's great group of blokes on the
course but the room is like the weather - %wdesc:desc% and it gets hard to
follow late in the day."
由于我不会深入探讨的原因,我将使用的散列中的一些键将包含点 (.) 或冒号 (:),但正则表达式对这些不起作用,例如在上面的示例中,只有 %place%
被正确替换。顺便说一下,我的代码是基于 this example .
非常感谢对正则表达式的任何帮助,或者可能有更好的方法...
最佳答案
您可以将其放宽并使用“不是 % 的任何序列”作为可替换标记:
$text =~ s/%([^%]+)%/$fill{$1}/g;
关于regex - 使用散列的 Perl 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969642/