I have a list of around 5000 words. I want to find the longest prefix match among those words for a given word. For example, in my list I have :
1
121
12234
20345
21345
Now If I search for 12134 the result will be 121 (longest match). I know it can be done in different ways. But, what should be the most efficient way ?
#!/usr/bin/env perl
use strict;
use warnings;
my @prefixes = qw(
1
121
12234
20345
21345
);
my $num = '12134';
my ($longest) = sort { length $b <=> length $a } grep { 0 == index $num, $_ } @prefixes;
print "$longest\n";
Outputs
121