Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to precompile a regex in Perl?

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.

like image 535
Sam Lee Avatar asked Jun 04 '09 20:06

Sam Lee


People also ask

How do I match a new line in a regular expression in Perl?

i think this will work,using the /s modifier, which mnemonically means to "treat string as a single line". This changes the behaviour of "." to match newline characters as well. In order to match the beginning of this comment to the end, we add the /s modifier like this: $str =~ s/<!

How do I match a pattern in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.

Does compiling regex make it faster?

I created a much simpler test that will show you that compiled regular expressions are unquestionably faster than not compiled. Here, the compiled regular expression is 35% faster than the not compiled regular expression.

Does Perl use regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.


1 Answers

For literal (static) regexes there's nothing to do -- Perl will only compile them once.

if ($var =~ /foo|bar/) {     # ... } 

For regexes stored in variables you have a couple of options. You can use the qr// operator to build a regex object:

my $re = qr/foo|bar/;  if ($var =~ $re) {     # ... } 

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 /o option to promise Perl that it will never change:

my $pattern = 'foo|bar';  if ($var =~ /$pattern/o) {     # ... } 

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 /o is probably a premature micro-optimization. It's also a potential pitfall. If the variable has changed using /o would cause Perl to use the old regex anyway. That could lead to hard-to-diagnose bugs.

like image 95
Michael Carman Avatar answered Sep 21 '22 21:09

Michael Carman