File Coverage

blib/lib/Regexp/Trie.pm
Criterion Covered Total %
statement 9 36 25.0
branch 0 16 0.0
condition 0 5 0.0
subroutine 3 7 42.8
pod 0 3 0.0
total 12 67 17.9


line stmt bran cond sub pod time code
1             #
2             # $Id: Trie.pm,v 0.2 2006/04/27 05:24:40 dankogai Exp dankogai $
3             #
4              
5             package Regexp::Trie;
6 1     1   26119 use 5.008001;
  1         3  
  1         33  
7 1     1   5 use strict;
  1         2  
  1         91  
8 1     1   5 use warnings;
  1         6  
  1         460  
9              
10             our $VERSION = sprintf "%d.%02d", q$Revision: 0.2 $ =~ /(\d+)/g;
11              
12             # use overload q("") => sub { shift->regexp };
13              
14 0     0 0   sub new{ bless {} => shift }
15             sub add{
16 0     0 0   my $self = shift;
17 0           my $str = shift;
18 0           my $ref = $self;
19 0           for my $char (split //, $str){
20 0   0       $ref->{$char} ||= {};
21 0           $ref = $ref->{$char};
22             }
23 0           $ref->{''} = 1; # { '' => 1 } as terminator
24 0           $self;
25             }
26             sub _regexp{
27 0     0     my $self = shift;
28 0 0 0       return if $self->{''} and scalar keys %$self == 1; # terminator
29 0           my (@alt, @cc);
30 0           my $q = 0;
31 0           for my $char (sort keys %$self){
32 0           my $qchar = quotemeta $char;
33 0 0         if (ref $self->{$char}){
34 0 0         if (defined (my $recurse = _regexp($self->{$char}))){
35 0           push @alt, $qchar . $recurse;
36             }else{
37 0           push @cc, $qchar;
38             }
39             }else{
40 0           $q = 1;
41             }
42             }
43 0           my $cconly = !@alt;
44 0 0         @cc and push @alt, @cc == 1 ? $cc[0] : '['. join('', @cc). ']';
    0          
45 0 0         my $result = @alt == 1 ? $alt[0] : '(?:' . join('|', @alt) . ')';
46 0 0         $q and $result = $cconly ? "$result?" : "(?:$result)?";
    0          
47 0           return $result;
48             }
49 0     0 0   sub regexp{ my $str = shift->_regexp; qr/$str/ }
  0            
50              
51             1;
52             __END__