#! perl use strict; use warnings; use Algorithm::Diff qw( LCS ); use constant { CASE_SENSITIVE => 0, DICTIONARY_FILE => 'words.txt', MINIMUM_MATCH => 2, }; print "Enter the target word: "; chomp(my $target = ); my @target = split //, CASE_SENSITIVE ? $target : lc $target; open(my $in, '<', DICTIONARY_FILE) or die "Cannot open file '" . DICTIONARY_FILE . "' for reading: $!"; my %substrings; while (my $word = <$in>) { chomp $word; my @word = split //, CASE_SENSITIVE ? $word : lc $word; my @lcs = LCS(\@target, \@word); $substrings{ join('', @lcs) } = $word if @lcs >= MINIMUM_MATCH; } close $in or die "Cannot close file '" . DICTIONARY_FILE . "': $!"; if (%substrings) { my @matches = sort { length $a <=> length $b } keys %substrings; print "The closest match is: ", $substrings{ $matches[-1] }, "\n"; } else { print "No matches found\n"; }