in reply to precompiling regular expressions
First, s/// doesn't compile the pattern more than once per pass of /g.
Compiles at most once per call to f, even if it replaces twice:
sub f { my $pat = $_[0]; (my $str = 'abba') =~ s/$pat//g; }
Same:
sub f { my $re = qr/$_[0]/; (my $str = 'abba') =~ s/$re//g; }
Now to explain the "at most" bit.
Compiles twice:
sub f { my $pat = $_[0]; (my $str = 'abba') =~ s/$pat//g; } f('a') f('b')
Compiles once (since Perl notices the pattern doesn't change):
sub f { my $pat = $_[0]; (my $str = 'abba') =~ s/$pat//g; } f('b') f('b') f('b')
Finally, how can you avoid excessive recompiling?
Compiles four times (since the pattern keeps changing):
sub f { my $pat = $_[0]; (my $str = 'abba') =~ s/$pat//g; } f('a') f('b') f('a') f('b')
Compiles two times:
my $re_a = qr/a/; my $re_b = qr/b/; sub f { my $re = $_[0]; (my $str = 'abba') =~ s/$re//g; } f($re_a); f($re_b); f($re_a); f($re_b);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: precompiling regular expressions
by Anonymous Monk on Oct 22, 2010 at 10:09 UTC | |
by ikegami (Patriarch) on Oct 22, 2010 at 10:34 UTC |