假设我有一个动态生成正则表达式并进行匹配的函数。
例如,在以下函数中,
我想知道每次函数被评估时,匿名正则表达式对象是否会"编译",或者是否有缓存,使得相同的字符串不会导致额外的正则表达式对象被编译。
另外,假设Perl解释器没有进行缓存,编译一个正则表达式对象是否足够昂贵,值得缓存(可能在XS扩展中)?
例如,在以下函数中,
match_here
会在正则表达式开头插入\G
锚定符号。这简化了API,因为调用者不需要记住在模式中包含pos
锚定符号。#!/usr/bin/env perl
use strict;
use warnings;
use Carp;
use Data::Dumper;
sub match_here {
my ($str, $index, $rg) = @_;
pos($str) = $index;
croak "index ($index) out of bounds" unless pos($str) == $index;
my $out;
if ($str =~ /\G$rg/) {
$out = $+[0];
}
return $out;
}
# no match starting at position 0
# prints '$VAR1 = undef;'
print Dumper(match_here("abc", 0, "b+"));
# match from 1 to 2
# prints '$VAR1 = 2;'
print Dumper(match_here("abc", 1, "b+"));
我想知道每次函数被评估时,匿名正则表达式对象是否会"编译",或者是否有缓存,使得相同的字符串不会导致额外的正则表达式对象被编译。
另外,假设Perl解释器没有进行缓存,编译一个正则表达式对象是否足够昂贵,值得缓存(可能在XS扩展中)?
rg
是否算作独立或相同变量?我不确定如何理解它。 - Greg Nisbet/$re/
)时,才会使用现有的编译模式。这意味着传递qr/b+/
而不是"b+"
是没有帮助的。 - ikegami