Patterns without interpolation are compiled when their quoting operator (m//, s///, qr//) is compiled. /o shouldn't matter one bit for those, so I won't discuss them.
Patterns with interpolation are compiled when their quoting operator (m//, s///, qr//) is executed.
Perl caches compiled regex patterns to avoid needless recompilation in situations like the following:
# Compiles each pattern once since m// realises # you're using the same pattern twice in a row. for my $re (qw( foo bar )) { for (1..2) { /$re/ } }
A match or substitution operator can only resuse the last regex is compiled, so the following isn't efficient:
# Compiles each pattern twice for (1..2) { for my $re (qw( foo bar )) { /$re/ } }
You can use qr// to precompile a pattern.
# Compiles each pattern once my @res = map qr/$_/, qw( foo bar ); for (1..2) { for my $re (@res) { /$re/ } }
Note that Perl currently flattens and recompiles compiled patterns interpolated into another pattern.
# Doesn't recompile $re if it's a qr//. /$re/ # Stringifies and recompiles $re if it's a qr//, # but it should be subject to the caching mentioned above. /x$re/
This should be optimised in the future.
In reply to Re: Regexp optimization - /o option better than precompiled regexp?
by ikegami
in thread Regexp optimization - /o option better than precompiled regexp?
by Hessu
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |