-
Notifications
You must be signed in to change notification settings - Fork 33
/
word_roots.pl
executable file
·59 lines (45 loc) · 1.11 KB
/
word_roots.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 11th September 2014
# https://github.com/trizen
# Find the minimum word derivations for a list of words
use 5.016;
use strict;
use warnings;
no warnings 'recursion';
sub make_tree {
my ($fh) = @_;
my %table;
while (defined(my $word = unpack('A*', scalar(<$fh>) // last))) {
my $ref = \%table;
foreach my $char (split //, $word) {
$ref = $ref->{$char} //= {};
}
undef $ref->{$word};
}
return \%table;
}
sub traverse(&$) {
my ($code, $hash) = @_;
foreach my $key (my @keys = sort keys %{$hash}) {
__SUB__->($code, $hash->{$key});
if ($#keys > 0) {
my $count = 0;
my $ref = my $val = delete $hash->{$key};
while (my ($key) = each %{$ref}) {
$ref = $val = $ref->{$key // last} // ($code->(substr($key, 0, length($key) - $count)), last);
++$count;
}
}
}
}
traverse { say shift } make_tree(@ARGV ? \*ARGV : \*DATA);
__END__
deodorant
decor
decadere
plecare
placere
plecat
jaguar