re pragma 可以生成您似乎感兴趣的信息。
use strict;
use warnings;
use re qw(Debug DUMP);
my $re = qr/square[\s-]*dance/;
'Let\'s go to the square dance!' =~ $re;
输出:
Compiling REx "square[\s-]*dance"
Final program:
1: EXACT <square> (4)
4: STAR (17)
5: ANYOF[\11\12\14\15 \-][+utf8::IsSpacePerl] (0)
17: EXACT <dance> (20)
20: END (0)
anchored "square" at 0 floating "dance" at 6..2147483647 (checking anchored) minlen 11
Freeing REx: "square[\s-]*dance"
不幸的是,似乎没有程序化挂钩来获取此信息。您必须拦截 STDERR 上的输出并对其进行解析。粗略的概念验证:
sub build_regexp {
my $string = shift;
my $dump;
# save off STDERR and redirect to scalar
open my $stderr, '>&', STDERR or die "Can't dup STDERR";
close STDERR;
open STDERR, '>', \$dump or die;
# Compile regexp, capturing DUMP output in $dump
my $re = do {
use re qw(Debug DUMP);
qr/$string/;
};
# Restore STDERR
close STDERR;
open STDERR, '>&', $stderr or die "Can't restore STDERR";
# Parse DUMP output
my @atoms = grep { /EXACT/ } split("\n", $dump);
return $re, @atoms;
}
这样使用:
my ($re, @atoms) = build_regexp('square[\s-]*dance');
$re 包含模式,@atoms 包含模式的文字部分的列表。在这种情况下,那是
1: EXACT <square> (4)
17: EXACT <dance> (20)