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

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