blib/lib/Map/Tube/Plugin/FuzzyFind.pm

filter: Statementstmt 12.2% 25 / 205 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 40 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 30.7% 8 / 26 Podpod 100% 2 / 2 totaltotal 8.6% 35 / 404 CC 73 SCAR 63.6
CC
73
Cov
7%
__ANON__
1056.0
fuzzy_find
812.0
__ANON__
20.0
CRAP 579.8
↑ Summary
1 # -*- perl -*-
2 #
3 # Author: Gisbert W. Selke, TapirSoft Selke & Selke GbR.
4 #
5 # Copyright (C) 2015--2026 Gisbert W. Selke. All rights reserved.
6 # This package is free software; you can redistribute it and/or
7 # modify it under the same terms as Perl itself.
8 #
9 # Mail: gws@cpan.org
10 #
11 package Map::Tube::Plugin::FuzzyFind;
12
13 3 ▶use 5.14.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use version 0.77 ( );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 3 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 3 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
21
22 3 our $VERSION = version->declare('v0.82.1');
23
24 =head1 NAME
25
26 Map::Tube::Plugin::FuzzyFind - Map::Tube add-on for finding stations and lines by inexact name.
27
28 =head1 VERSION
29
30 Version 0.82.1
31
32
33 =head1 DESCRIPTION
34
35 This is an add-on for L<Map::Tube> to find stations and lines by name, possibly
36 partly or inexactly specified. The module is a Moo role which gets plugged into the
37 Map::Tube::* family automatically once it is installed.
38
39
40 =head1 SYNOPSIS
41
42 use strict; use warnings;
43 use Map::Tube::London;
44
45 my $tube = Map::Tube::London->new();
46
47 print 'line matches exactly: ',
48 scalar( $tube->fuzzy_find( search => 'erloo',
49 objects => 'lines' ) ), "\n";
50 print 'line contains : ',
51 scalar( $tube->fuzzy_find( search => 'erloo',
52 objects => 'lines',
53 method => 'in' ) ), "\n";
54 print 'same thing : ',
55 scalar( $tube->fuzzy_find( 'erloo',
56 objects => 'lines',
57 method => 'in' ) ), "\n";
58 print 'same thing : ',
59 scalar( $tube->fuzzy_find( { search => 'erloo',
60 objects => 'lines',
61 method => 'in' } ) ), "\n";
62 print 'station re : ',
63 join( ' ', $tube->fuzzy_find( search => qr/[htrv]er/i,
64 objects => 'stations' ) ), "\n";
65 print 'station re : ',
66 join( ' ', $tube->fuzzy_find( search => '[htrv]er',
67 objects => 'stations',
68 method => 'regex' ) ), "\n";
69 print 'line fuzzy : ',
70 scalar( $tube->fuzzy_find( search => 'Kyrkle',
71 objects => 'stations',
72 method => 'levenshtein' ) ), "\n";
73
74
75 =head1 METHODS
76
77 =head2 fuzzy_find(%args)
78
79 Find a tube line or station by some pattern, which may be partly or
80 inexactly specified. In array context, a (possibly empty) array of
81 Map::Tube::{Line,Node} objects is returned that match the pattern. If
82 the matching method employed provides a measure of similarity, the
83 result set will be ordered by decreasing similarity. Otherwise, it will
84 be ordered alphabetically. In scalar context, a Map::Tube::{Line,Node}
85 object (or undef) is returned. In the case of more than one match, the
86 most similar or the alphabetically first match will be returned, as
87 applicable to the matching method.
88
89 C<%args> is a hash of optional named parameters to guide actions. It may
90 be specified as a hash or as a reference to a hash. For convenience, the
91 search pattern may be specified as the first argument, outside the hash.
92 While formally all arguments are optional, not specifying a search
93 pattern will, predictably, not produce any exciting result.
94
95 =over 4
96
97 =item search=...
98
99 The pattern to be searched for. It may be a string or a (possibly
100 precompiled) regular expression. The latter requires the matching
101 method (cf. below) to be C<'regex'>.
102
103 =item objects=...
104
105 This specifies whether stations or lines should be found. The value should
106 be either C<'lines'> or C<'stations'>. (C<'nodes'> is a synonym for
107 C<'stations'>.) If it is none of these, then both lines and stations will
108 be searched.
109
110 =item method=...
111
112 The method for matching. If this parameter is missing, the default is to
113 use C<'regex'> if the pattern is a precompiled regex, or C<'exact'>
114 otherwise. Otherwise, the value should be one of the following.
115
116 =over 4
117
118 =item 'exact'
119
120 Exact matching will be performed (up to case). This is also the default
121 method if only a search string (without any further arguments) is supplied.
122
123 =item 'start'
124
125 The given string pattern must match at the beginning of the line or station
126 name (up to case).
127
128 =item 'in'
129
130 The given string pattern must match somewhere within the line or station
131 name (up to case).
132
133 =item 're' or 'regex'
134
135 The given pattern is matched as a regex (case-insensitively) against the
136 line or station names. The pattern may also be specified as a precompiled
137 regex. In this case, its case sensitivity will be used unaltered.
138
139 =item 'soundex'
140
141 All names matching according to the soundex algorithm
142 (see L<Text::Soundex>) will be returned. Actually, a variant of Donald E. Knuth's
143 original algorithm is used which also tries to cope with non-ASCII characters.
144 It works well only for English-like words.
145
146 =item 'phonix'
147
148 All names matching according to the phonix algorithm
149 (see L<Text::Phonetic::Phonix>) will be returned. This is an alternative to soundex.
150
151 =item 'daitchmokotoff' or 'dmsoundex'
152
153 All names matching according to the Daitch-Motokoff algorithm
154 (see L<Text::Phonetic::DaitchMotokoff>) will be returned. This alternative to soundex
155 may be preferable for Slavic and Yiddish names.
156
157 =item 'koeln'
158
159 All names matching according to the Koeln phonetic encoding
160 (see L<Text::Phonetic::Koeln>) will be returned. This alternative to soundex
161 may work better for German names, as well as for longer names.
162
163 =item 'metaphone'
164
165 All names matching according to the Metaphone algorithm
166 (see L<Text::Metaphone>) will be returned. This is a method that strives to be
167 "a modern version of soundex". It is also tuned towards English words.
168
169 =item 'doublemetaphone'
170
171 All names matching according to the DoubleMetaphone algorithm
172 (see L<Text::DoubleMetaphone>) will be returned. This was developped as an improvement
173 on Metaphone.
174
175 =item 'levenshtein' or 'editdistance'
176
177 The closest names as calculated by the Levenshtein edit distance
178 (see L<Text::Levenshtein>) will be returned.
179
180 =item 'levenshteindamerau' or 'damerau'
181
182 The closest names as calculated by the Levenshtein-Damerau edit distance
183 (see L<Text::Levenshtein::Damerau>) will be returned. This is an
184 alternative to the edit distance defined by Levenshtein.
185
186 =item 'jarowinkler'
187
188 The closest names as calculated by the Jaro-Winkler edit distance (see
189 L<Text::JaroWinkler>) will be returned. This is an alternative to the
190 edit distance defined by Levenshtein.
191
192 =item 'ngrams'
193
194 The closest names as calculated by a comparison of trigrams
195 (see L<String::Trigram>) will be returned. (Future versions may include
196 n-grams for n other than 3).
197
198 =item 'fuzzy'
199
200 Currently, this is a synonym for C<'levenshtein'>.
201 I<This may change in the future.>
202
203 =item a code ref
204
205 Reserved for future use.
206
207 =item ...
208
209 Further fuzzy matchers may be added in the future according to interest.
210
211 =back
212
213 =item maxdist=...
214
215 For some matchers that define a metric on strings (like Levenshtein),
216 this may specify the maximum allowable distance from the pattern specified.
217 The default is half the length of the pattern. If 0 is specified, no
218 limit will be applied. Note that, in array context, this may result in a large
219 number of returned values. In scalar context, a non-null value (including the
220 default value) may lead to no result being returned.
221
222 =item maxsize=...
223
224 In array context, this may be used to specify the maximum number of values
225 to return, in order to prevent flooding. There is no default. If 0 is specified,
226 no limit will be applied. In scalar context, this parameter is disregarded.
227
228 =item maxcodelen=...
229
230 (Used only for Metaphone) The original definition of the Metaphone algorithm uses
231 a maximum of 4 characters for the encoded strings (just like Soundex). 4 is
232 also used here by default. This parameter allows to set other values.
233
234
235 =back
236
237 =head2 list_fuzzy_matchers( )
238
239 Provide an alphabetic list of all supported fuzzy matching algorithms.
240 Algorithms that are known but not installed on your machine will be
241 marked appropriately.
242
243 =cut
244
245 # Note: The code comes on purpose in just one sub, in order to prevent
246 # name space pollution of Map::Tube::xxx. Other solutions are possible,
247 # but currently it is felt they would introduce more hassle than clarity.
248
249
250 0 ▶sub fuzzy_find { ## no critic(Subroutines::ProhibitExcessComplexity)
Subroutine fuzzy_find: not called CC=28 SCAR=67.0
Pod documented
251 0 my( $self, @tmpargs ) = @_;
252 0 my( %args, $pattern );
253
254 0 my %matchers = @{ $self->_known_matchers( ) };
255
256 # unify the different ways of passing arguments:
257 0 ▶ if ( scalar(@tmpargs) == 1 ) {
Branch: 3 branches
BranchTrueFalseTotal
if (scalar @tmpargs == 1) { } 0 0 0
elsif (scalar @tmpargs == 2 and ref $tmpargs[1] eq 'HASH') { } 0 0 0
elsif (scalar(@tmpargs) % 2) { } 0 0 0
258 0 ▶ if ( ref( $tmpargs[0] ) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $tmpargs[0] eq 'HASH') { } 0 0 0
259
260 # everything in just one hash ref.
261 0 %args = %{ $tmpargs[0] };
262 0 $pattern = $args{search};
263 } else {
264
265 # must be a lone string or regex, with no other args
266 0 $pattern = $tmpargs[0];
267 }
268 ▶ } elsif ( ( scalar(@tmpargs) == 2 ) && ( ref( $tmpargs[1] ) eq 'HASH' ) ) {
Condition0%0/3
scalar @tmpargs == 2 and ref $tmpargs[1] eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
scalar @tmpargs == 2 and ref $tmpargs[1] eq "HASH"
scalar @tmpargs == 2 ref $tmpargs[1] eq "HASH"
Truth table0%0/3
A and B
A= scalar @tmpargs == 2B= ref $tmpargs[1] eq "HASH"
ABresult
0X0
100
111
269
270 # Pattern plus hash ref
271 0 %args = %{ $tmpargs[1] };
272 0 $pattern = $tmpargs[0]; # bad luck if conflicting specs...
273 } elsif ( scalar(@tmpargs) % 2 ) {
274
275 # odd number of args >= 3. Must be pattern plus hash
276 0 $pattern = shift(@tmpargs);
277 0 %args = @tmpargs;
278 } else {
279
280 # Even number of args >= 2. This must be a real hash.
281 0 %args = @tmpargs;
282 0 $pattern = $args{search};
283 } ## end else [ if ( scalar(@tmpargs) ...)]
284
285 0 ▶ return unless defined $pattern;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pattern 0 0 0
286
287 # Now all args are in the non-empty %args hash, and we know what to search for.
288 0 ▶ $args{objects} ||= '';
Condition0%0/2
$args{"objects"} ||= ""
l!l
00
MC/DC0%0/1
$args{"objects"} ||= ""
$args{"objects"}
Truth table0%0/2
A
A= $args{"objects"}
Aresult
11
00
289 0 ▶ $args{objects} = 'stations' if ( $args{objects} eq 'nodes' );
Branch: 1 branch
BranchTrueFalseTotal
if $args{"objects"} eq "nodes" 0 0 0
290 0 ▶ $args{maxsize} ||= 0;
Condition0%0/2
$args{"maxsize"} ||= 0
l!l
00
MC/DC0%0/1
$args{"maxsize"} ||= 0
$args{"maxsize"}
Truth table0%0/2
A
A= $args{"maxsize"}
Aresult
11
00
291 0 ▶ $args{maxcodelen} //= 4; # used only for Metaphone, optionally
Condition0%0/2
$args{"maxcodelen"} //= 4
l!l
00
MC/DC0%0/1
$args{"maxcodelen"} //= 4
$args{"maxcodelen"}
Truth table0%0/2
A
A= $args{"maxcodelen"}
Aresult
11
00
292 0 ▶ $args{method} ||= ( ref( $args{search} ) eq 'Regexp' ) ? 'regex' : 'exact';
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'search'} eq 'Regexp' ? : 0 0 0
Condition0%0/3
$args{"method"} ||= ref $args{"search"} eq "Regexp" ? "regex" : "exact"
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"method"} ||= ref $args{"search"} eq "Regexp" ? "regex" : "exact"
$args{"method"} ref $args{"search"} eq "Regexp" ? "regex" : "exact"
Truth table0%0/3
A ||= B
A= $args{"method"}B= ref $args{"search"} eq "Regexp" ? "regex" : "exact"
ABresult
1X1
011
000
293
294 # Procure the list of things in which to search
295 0 my $source;
296 0 ▶ if ( $args{objects} eq 'lines' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'objects'} eq 'lines') { } 0 0 0
elsif ($args{'objects'} eq 'stations') { } 0 0 0
297 0 $source = $self->get_lines();
298 } elsif ( $args{objects} eq 'stations' ) {
299 # $source = [ values %{ $self->nodes() } ]; # *** replace by $self->get_stations() ***
300 0 $source = $self->get_stations( ); # *** replace by $self->get_stations() ***
301 } else {
302 # $source = [ @{ $self->get_lines() }, values %{ $self->nodes() } ]; # *** replace by $self->get_stations() ***
303 0 $source = [ @{ $self->get_lines() }, @{ $self->get_stations( ) } ]; # *** replace by $self->get_stations() ***
304 }
305
306 # Find the numerical index of the method which we should use:
307 0 ▶ my( $nmethod, @modules ) = @{ $matchers{ lc( $args{method} ) } // [ -1, undef ] };
Condition0%0/2
$matchers{lc $args{"method"}} // [-1, undef]
l!l
00
MC/DC0%0/1
$matchers{lc $args{"method"}} // [-1, undef]
$matchers{lc $args{"method"}}
Truth table0%0/2
A
A= $matchers{lc $args{"method"}}
Aresult
11
00
308
309 0 my @result;
310 0 ▶ if ( $nmethod == 1 ) { ## no critic(ControlStructures::ProhibitCascadingIfElse)
Branch: 5 branches
BranchTrueFalseTotal
if ($nmethod == 1) { } 0 0 0
elsif ($nmethod == 2) { } 0 0 0
elsif ($nmethod == 3) { } 0 0 0
elsif ($nmethod == 4) { } 0 0 0
elsif ($nmethod >= 5) { } 0 0 0
311
312 # Exact matching (up to case)
313 0 $pattern = lc($pattern);
314 0 @result = sort { $a->name() cmp $b->name() } grep { lc( $_->name() ) eq $pattern } @{$source};
315 } elsif ( $nmethod == 2 ) {
316
317 # Match at start
318 0 $pattern = lc($pattern);
319 0 @result = sort { $a->name() cmp $b->name() } grep { index( lc( $_->name() ), $pattern ) == 0 } @{$source};
320 } elsif ( $nmethod == 3 ) {
321
322 # Match some substring
323 0 $pattern = lc($pattern);
324 0 @result = sort { $a->name() cmp $b->name() } grep { index( lc( $_->name() ), $pattern ) >= 0 } @{$source};
325 } elsif ( $nmethod == 4 ) {
326
327 # Match regex
328 0 ▶ $pattern = qr/$pattern/i unless ref($pattern) eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pattern eq "Regexp" 0 0 0
329 0 @result = sort { $a->name() cmp $b->name() } grep { $_->name() =~ $pattern } @{$source};
330 # } elsif ( ( $nmethod >= 5 ) && ( $nmethod <= $maxmethod ) ) {
331 } elsif ( $nmethod >= 5 ) {
332
333 # Use some well-known fuzzy matcher
334 # *** This needs to be cleaned up.
335 0 my( $loaded, $matcher );
336 0 $pattern = lc($pattern);
337 0 $pattern =~ s/\s+//g;
338 0 ▶ try {
Subroutine __ANON__: not called CC=32 SCAR=69.6
339 0 ▶ if ( $nmethod == 5 ) {
Branch: 11 branches
BranchTrueFalseTotal
if ($nmethod == 5) { } 0 0 0
elsif ($nmethod == 6) { } 0 0 0
elsif ($nmethod == 7) { } 0 0 0
elsif ($nmethod == 8) { } 0 0 0
elsif ($nmethod == 9) { } 0 0 0
elsif ($nmethod == 10) { } 0 0 0
elsif ($nmethod == 11) { } 0 0 0
elsif ($nmethod == 12) { } 0 0 0
elsif ($nmethod == 13) { } 0 0 0
elsif ($nmethod == 14) { } 0 0 0
elsif ($nmethod == 15) { } 0 0 0
340
341 # Knuth's soundex, or some variant thereof, adapted for non-ASCII codes.
342 0 $loaded = eval qq{ require $modules[0]; 1 };
343 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
344 0 my $pattern_soundex = Text::Soundex::soundex_unicode($pattern);
345 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
346 0 ▶ return ( Text::Soundex::soundex_unicode( $_[0] ) eq $pattern_soundex ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
Text::Soundex::soundex_unicode($_[0]) eq $pattern_soundex ? : 0 0 0
347 0 };
348 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
349 } elsif ( $nmethod == 6 ) {
350
351 # Phonix, (claiming to be) "an improved Soundex". This variant keeps the first letter (like original Soundex).
352 0 $loaded = eval qq{ require $modules[0]; 1 };
353 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
354 0 my $obj = Text::Phonetic::Phonix->new( );
355 0 my $pattern_metacode = $obj->encode($pattern);
356 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
357 0 ▶ return ( $obj->encode( $_[0] ) eq $pattern_metacode ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$obj->encode($_[0]) eq $pattern_metacode ? : 0 0 0
358 0 };
359 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
360 } elsif ( $nmethod == 7 ) {
361
362 # Daitch-Mokotoff Soundex, a Soundex variant geared towards Slavic and Yiddish.
363 0 $loaded = eval qq{ require $modules[0]; 1 };
364 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
365 0 my $obj = Text::Phonetic::DaitchMokotoff->new( );
366 0 my @pattern_metacodes = @{ $obj->encode($pattern) };
367 # Daitch-Mokotoff returns up to two values. Results are always returned as an Arrayref.
368 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
369 0 for my $strcode( @{ $obj->encode( $_[0] ) } ) {
370 0 for ( @pattern_metacodes ) {
371 0 ▶ return 0 if ( $_ eq $strcode );
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq $strcode 0 0 0
372 }
373 }
374 0 return 1;
375 0 };
376 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
377 } elsif ( $nmethod == 8 ) {
378
379 # "Koeln Phonetic", a Soundex variant geared towards German. Also towards longer words.
380 0 $loaded = eval qq{ require $modules[0]; 1 };
381 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
382 0 my $obj = Text::Phonetic::Koeln->new( );
383 0 my $pattern_metacode = $obj->encode($pattern);
384 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
385 0 ▶ return ( $obj->encode( $_[0] ) eq $pattern_metacode ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$obj->encode($_[0]) eq $pattern_metacode ? : 0 0 0
386 0 };
387 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
388 } elsif ( $nmethod == 9 ) {
389
390 # Metaphone, (claiming to be) "A modern Soundex". Still with a slant towards English pronunciation.
391 0 $loaded = eval qq{ require $modules[0]; 1 };
392 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
393 0 my $maxcodelen = $args{maxcodelen};
394 0 my $pattern_metacode = Text::Metaphone::Metaphone($pattern, $maxcodelen);
395 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
396 0 ▶ return ( Text::Metaphone::Metaphone( $_[0], $maxcodelen ) eq $pattern_metacode ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
Text::Metaphone::Metaphone($_[0], $maxcodelen) eq $pattern_metacode ? : 0 0 0
397 0 };
398 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
399 } elsif ( $nmethod == 10 ) {
400
401 # DoubleMetaphone, an improved Metaphone, better taking into account several non-English languages.
402 # Note: There may be up to two encodings for each input.
403 0 $loaded = eval qq{ require $modules[0]; 1 };
404 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
405 0 my @pattern_metacodes = Text::DoubleMetaphone::double_metaphone($pattern);
406 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
407 0 for my $strcode( Text::DoubleMetaphone::double_metaphone( $_[0] ) ) {
408 0 for ( @pattern_metacodes ) {
409 0 ▶ return 0 if ( $_ eq $strcode );
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq $strcode 0 0 0
410 }
411 }
412 0 return 1;
413 0 };
414 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
415 } elsif ( $nmethod == 11 ) {
416
417 # Phonem, a Soundex-analogue better taking into account Germanic lanuages (and their penchant for long words)
418 0 $loaded = eval qq{ require $modules[0]; 1 };
419 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
420 0 my $obj = Text::Phonetic::Phonem->new( );
421 0 my $pattern_metacode = $obj->encode($pattern);
422 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
423 0 ▶ return ( $obj->encode( $_[0] ) eq $pattern_metacode ) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$obj->encode($_[0]) eq $pattern_metacode ? : 0 0 0
424 0 };
425 0 $args{maxdist} = 0.5; # so that exactly the matches will be retained in the map - sort - grep.
426 } elsif ( $nmethod == 12 ) {
427
428 # Levenshtein edit distance
429 0 $loaded = eval qq{ require $modules[0]; 1 };
430 0 ▶ if ($loaded) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loaded) { } 0 0 0
431 0 ▶ $matcher = sub { Text::Levenshtein::XS::distance( $_[0], $pattern ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
432 } else {
433 0 $loaded = eval qq{ require $modules[1]; 1 };
434 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
435 0 ▶ $matcher = sub { Text::Levenshtein::distance( $_[0], $pattern ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
436 }
437 0 ▶ $args{maxdist} ||= int( ( length($pattern) + 1.000001 ) / 2 );
Condition0%0/3
$args{"maxdist"} ||= int((length($pattern) + "1.000001") / 2)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"maxdist"} ||= int((length($pattern) + "1.000001") / 2)
$args{"maxdist"} int((length($pattern) + "1.000001") / 2)
Truth table0%0/3
A ||= B
A= $args{"maxdist"}B= int((length($pattern) + "1.000001") / 2)
ABresult
1X1
011
000
438 } elsif ( $nmethod == 13 ) {
439
440 # Levenshtein-Damerau edit distance: almost the same as Levenshtein, but also counts adjacent swaps as one operation
441 0 $loaded = eval qq{ require $modules[0]; 1 };
442 0 ▶ if ($loaded) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loaded) { } 0 0 0
443 0 ▶ $matcher = sub { Text::Levenshtein::Damerau::XS::xs_edistance( $_[0], $pattern ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
444 } else {
445 0 $loaded = eval qq{ require $modules[1]; 1 };
446 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
447 0 ▶ $matcher = sub { Text::Levenshtein::Damerau::edistance( $_[0], $pattern ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
448 }
449 0 ▶ $args{maxdist} ||= int( ( length($pattern) + 1.000001 ) / 2 );
Condition0%0/3
$args{"maxdist"} ||= int((length($pattern) + "1.000001") / 2)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"maxdist"} ||= int((length($pattern) + "1.000001") / 2)
$args{"maxdist"} int((length($pattern) + "1.000001") / 2)
Truth table0%0/3
A ||= B
A= $args{"maxdist"}B= int((length($pattern) + "1.000001") / 2)
ABresult
1X1
011
000
450 } elsif ( $nmethod == 14 ) {
451
452 # Jaro-Winkler string distance.
453 # Originally yields a vale between 0 (very far) to 1 (identical).
454 # Distances are re-normalized to better fit with Levenshtein value range.
455 0 $loaded = eval qq{ require $modules[0]; 1 };
456 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
457 0 my $stretch = 2 * length($pattern);
458 0 ▶ $matcher = sub { $stretch * ( 1 - Text::JaroWinkler::strcmp95( $_[0], $pattern, length($_[0]) ) ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
459 0 ▶ $args{maxdist} ||= int( ( length($pattern) + 1.000001 ) / 2);
Condition0%0/3
$args{"maxdist"} ||= int((length($pattern) + "1.000001") / 2)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"maxdist"} ||= int((length($pattern) + "1.000001") / 2)
$args{"maxdist"} int((length($pattern) + "1.000001") / 2)
Truth table0%0/3
A ||= B
A= $args{"maxdist"}B= int((length($pattern) + "1.000001") / 2)
ABresult
1X1
011
000
460 } elsif ( $nmethod == 15 ) {
461
462 # Comparison by number of matching n-grams, by default 3-grams. (Can be changed with the windowsize argument.)
463 # This needs to be re-organised so that multiple calls with the same parameters
464 # (but different search strings) will re-use the string base (not the search string).
465 0 $loaded = eval qq{ require $modules[0]; 1 };
466 0 ▶ croak unless $loaded;
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 0 0 0
467 0 ▶ $args{maxdist} ||= length($pattern) / 2;
Condition0%0/3
$args{"maxdist"} ||= length($pattern) / 2
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"maxdist"} ||= length($pattern) / 2
$args{"maxdist"} length($pattern) / 2
Truth table0%0/3
A ||= B
A= $args{"maxdist"}B= length($pattern) / 2
ABresult
1X1
011
000
468 0 my %st_args;
469 0 $st_args{minSim} = 1 - $args{maxdist} / length($pattern);
470 0 ▶ $st_args{minSim} = 0 if ( $st_args{minSim} < 0 );
Branch: 1 branch
BranchTrueFalseTotal
if $st_args{"minSim"} < 0 0 0 0
471 0 ▶ $st_args{minSim} = 1 if ( $st_args{minSim} > 1 );
Branch: 1 branch
BranchTrueFalseTotal
if $st_args{"minSim"} > 1 0 0 0
472 0 ▶ $st_args{ngram} = $args{windowsize} || 3;
Condition0%0/2
$args{'windowsize'} || 3
l!l
00
MC/DC0%0/1
$args{'windowsize'} || 3
$args{'windowsize'}
Truth table0%0/2
A
A= $args{'windowsize'}
Aresult
11
00
473 0 $st_args{warp} = 2;
474 0 $st_args{cmpBase} = [$pattern];
475 0 my $trigrammer = String::Trigram->new(%st_args);
476 0 ▶ $matcher = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
477 0 my $str = $_[0];
478 0 $str =~ s/\s+//g;
479 0 my %result;
480 0 my $nresults = $trigrammer->getSimilarStrings( $str, \%result );
481 0 ▶ return $nresults ? ( ( 1 - $result{$pattern} ) * length($pattern) ) : ( length($pattern) + 1 );
Branch: 1 branch
BranchTrueFalseTotal
$nresults ? : 0 0 0
482 0 };
483 } ## end elsif ( $nmethod == 15 )
484 } ## end try
485 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
486 0 croak "Matcher module $modules[0] not loaded or not executed: $_";
487 0 };
488
489 # $matcher is now a coderef that takes one argument, viz., a string to match.
490 # It returns the distance from the pattern; the bigger the distance, the more dissimilar.
491 # In case of matchers that provide just a "match/no match" information,
492 # 0 means "match" and 1 means "no match".
493
494 0 my %name2obj = map { $_->name( ) => $_ } @{ $source };
495
496 0 my %distance = map { $_ => $matcher->( lc($_) ) } keys %name2obj;
497 0 @result = map { $name2obj{$_} }
498 0 ▶ sort { ( $distance{$a} <=> $distance{$b} ) || ( $a cmp $b ) }
Condition0%0/3
$distance{$a} <=> $distance{$b} || $a cmp $b
l!l&&r!l&&!r
000
MC/DC0%0/2
$distance{$a} <=> $distance{$b} || $a cmp $b
$distance{$a} <=> $distance{$b} $a cmp $b
Truth table0%0/3
A || B
A= $distance{$a} <=> $distance{$b}B= $a cmp $b
ABresult
1X1
011
000
499 0 ▶ grep { ( $args{maxdist} <= 0 ) || ( $distance{$_} <= $args{maxdist} ) } keys %distance;
Condition0%0/3
$args{'maxdist'} <= 0 || $distance{$_} <= $args{'maxdist'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'maxdist'} <= 0 || $distance{$_} <= $args{'maxdist'}
$args{'maxdist'} <= 0 $distance{$_} <= $args{'maxdist'}
Truth table0%0/3
A || B
A= $args{'maxdist'} <= 0B= $distance{$_} <= $args{'maxdist'}
ABresult
1X1
011
000
500 } else {
501
502 # nada
503 0 croak "Unknown matching method '$args{method}'";
504 }
505
506 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 0 0 0
507 0 ▶ return @result if ( ( $args{maxsize} == 0 ) || ( scalar(@result) <= $args{maxsize} ) );
Branch: 1 branch
BranchTrueFalseTotal
if $args{"maxsize"} == 0 or scalar @result <= $args{"maxsize"} 0 0 0
Condition0%0/3
$args{"maxsize"} == 0 or scalar @result <= $args{"maxsize"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"maxsize"} == 0 or scalar @result <= $args{"maxsize"}
$args{"maxsize"} == 0 scalar @result <= $args{"maxsize"}
Truth table0%0/3
A or B
A= $args{"maxsize"} == 0B= scalar @result <= $args{"maxsize"}
ABresult
1X1
011
000
508 0 return @result[ 0 .. ( $args{maxsize} - 1 ) ];
509 }
510
511 0 ▶ return unless @result;
Branch: 1 branch
BranchTrueFalseTotal
unless @result 0 0 0
512 0 return $result[0];
513 } ## end sub fuzzy_find
514
515
516 0 ▶sub list_fuzzy_matchers {
Subroutine list_fuzzy_matchers: not called CC=3 SCAR=24.8
Pod documented
517 0 my($self) = @_;
518
519 0 my @matchers = @{ $self->_known_matchers( ) };
520 0 my %matchers;
521 0 ▶ for (my $i=0; $i<scalar(@matchers); $i+=2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @matchers) 0 0 0
522 0 ▶ $matchers{$matchers[$i+1][0]} //= $matchers[$i];
Condition0%0/3
$matchers{$matchers[$i + 1][0]} //= $matchers[$i]
l!l&&r!l&&!r
000
MC/DC0%0/2
$matchers{$matchers[$i + 1][0]} //= $matchers[$i]
$matchers{$matchers[$i + 1][0]} $matchers[$i]
Truth table0%0/3
A //= B
A= $matchers{$matchers[$i + 1][0]}B= $matchers[$i]
ABresult
1X1
011
000
523 }
524 0 return sort values %matchers;
525 } ## end sub list_matchers
526
527
528 #
529 # Private methods
530 #
531
532
533 0 ▶sub _known_matchers {
Subroutine _known_matchers: not called CC=1 SCAR=6.9
534 # An array of known matching methods, some with alternate names, consecutively numbered,
535 # and the names of zero or more modules that implement them
536 0 my($self) = @_;
537 0 return [ exact => [ 1, undef ],
538 start => [ 2, undef ],
539 in => [ 3, undef ],
540 regex => [ 4, undef ],
541 re => [ 4, undef ],
542 soundex => [ 5, 'Text::Soundex' ],
543 phonix => [ 6, 'Text::Phonetic::Phonix' ],
544 daitchmokotoff => [ 7, 'Text::Phonetic::DaitchMokotoff' ],
545 dmsoundex => [ 7, 'Text::Phonetic::DaitchMokotoff' ],
546 koeln => [ 8, 'Text::Phonetic::Koeln' ],
547 metaphone => [ 9, 'Text::Metaphone' ],
548 doublemetaphone => [ 10, 'Text::DoubleMetaphone' ],
549 phonem => [ 11, 'Text::Phonetic::Phonem' ],
550 levenshtein => [ 12, 'Text::Levenshtein::XS', 'Text::Levenshtein' ],
551 editdistance => [ 12, 'Text::Levenshtein::XS', 'Text::Levenshtein' ],
552 fuzzy => [ 12, 'Text::Levenshtein::XS', 'Text::Levenshtein' ],
553 damerau => [ 13, 'Text::Levenshtein::Damerau::XS', 'Text::Levenshtein::Damerau' ],
554 levenshteindamerau => [ 13, 'Text::Levenshtein::Damerau::XS', 'Text::Levenshtein::Damerau' ],
555 jarowinkler => [ 14, 'Text::JaroWinkler' ],
556 ngrams => [ 15, 'String::Trigram' ],
557 ];
558
559 } ## end sub _known_matchers
560
561
562 =head1 AUTHOR
563
564 Gisbert W. Selke, TapirSoft Selke & Selke GbR, C<< <gws at cpan.org> >>
565
566 =head1 SEE ALSO
567
568 L<Map::Tube> and the various Text::* modules referenced above
569
570 =head1 CONTRIBUTORS
571
572 Thanks to Mohammad S Anwar, author of L<Map::Tube>, for that module, for great feedback,
573 discussions, advice, debugging help, and willingness to refactor his code.
574 Thanks to Slaven Rezic for extensive testing and valuable suggestions.
575
576 =head1 CONTRIBUTING
577
578 If you find a bug or have an idea for a useful extension, your contribution via
579 this module's issue tracker at L<https://github.com/gwselke/Map-Tube-Plugin-FuzzyFind/issues>
580 is welcome! Pull requests are also appreciated!
581
582 =head1 LICENSE AND COPYRIGHT
583
584 Copyright (C) 2015, 2025--2026 Gisbert W. Selke, Tapirsoft Selke & Selke GbR
585
586 This program is free software; you can redistribute it and/or modify it under
587 the terms of the the Artistic License (2.0). You may obtain a copy of the full
588 license at:
589
590 L<http://www.perlfoundation.org/artistic_license_2_0>
591
592 Any use, modification, and distribution of the Standard or Modified Versions is
593 governed by this Artistic License.By using, modifying or distributing the Package,
594 you accept this license. Do not use, modify, or distribute the Package, if you do
595 not accept this license.
596
597 If your Modified Version has been derived from a Modified Version made by someone
598 other than you,you are nevertheless required to ensure that your Modified Version
599 complies with the requirements of this license.
600
601 This license does not grant you the right to use any trademark, service mark,
602 tradename, or logo of the Copyright Holder.
603
604 This license includes the non-exclusive, worldwide, free-of-charge patent license
605 to make, have made, use, offer to sell, sell, import and otherwise transfer the
606 Package with respect to any patent claims licensable by the Copyright Holder that
607 are necessarily infringed by the Package. If you institute patent litigation
608 (including a cross-claim or counterclaim) against any party alleging that the
609 Package constitutes direct or contributory patent infringement,then this Artistic
610 License to you shall terminate on the date that such litigation is filed.
611
612 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
613 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
614 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
615 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
616 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
617 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
618 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
619
620 =cut
621
622 3 1; # End of Map::Tube::Plugin::FuzzyFind
↑ Summary