Is there a way to precompile a regex in Perl? I have one that I use many times in a program and it does not change between uses.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For literal (static) regexes there’s nothing to do — Perl will only compile them once.
For regexes stored in variables you have a couple of options. You can use the
qr//operator to build a regex object:This is handy if you want to use a regex in multiple places or pass it to subroutines.
If the regex pattern is in a string, you can use the
/ooption to promise Perl that it will never change:It’s usually better to not do that, though. Perl is smart enough to know that the variable hasn’t changed and the regex doesn’t need to be recompiled. Specifying
/ois probably a premature micro-optimization. It’s also a potential pitfall. If the variable has changed using/owould cause Perl to use the old regex anyway. That could lead to hard-to-diagnose bugs.