2005年10月18日星期二

regex compilation in Perl

昨天写一个简单的perl脚本处理一个比较大的文本文件时,觉得速度不太理想。想到regular expression多次匹配也许会有一些影响,记得不会变化的reg.ex.是可以编译的,编译后的执行速度应该会快一些,python里面的re模块 就提供compile函数。但对于perl,却不记得有这么个东西,在perl的帮助里面找了半天也没有找到。

最后还是用了google查到(也许应该先问它才是),很简单,在表达式后面添加一个修饰符(modifiier):

o - Compile a regular expression once
If you ever end up with a really long regular expression, you can use this modifier to compile it before it's used. This means that long and complicated expressions don't have to be compiled each time they're used.

The only thing you must remember is that if you use this modifier, you are promising Perl that you won't attempt to change it while the script is running. If you do, it won't be taken into account. There won't be an example of how to use this modifier, since if you're able to write regular expression this long and complicated, you're way ahead of anything I could tell you in this article!

没有评论: