-
Notifications
You must be signed in to change notification settings - Fork 33
/
search_by_prefix.pl
executable file
·72 lines (55 loc) · 1.36 KB
/
search_by_prefix.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
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 29 July 2016
# Website: https://github.com/trizen
# Analyzes a list of strings and returns those that have a certain prefix
package Search::ByPrefix;
use 5.014;
use strict;
use warnings;
sub new {
my ($class, %opt) = @_;
bless {table => $opt{table} // {}}, $class;
}
sub add {
my ($self, $key, $value) = @_;
my $ref = $self->{table};
foreach my $item (@$key) {
$ref = $ref->{$item} //= {};
push @{$ref->{values}}, \$value;
}
$self;
}
sub search {
my ($self, $pattern) = @_;
my $ref = $self->{table};
foreach my $item (@$pattern) {
if (exists $ref->{$item}) {
$ref = $ref->{$item};
}
else {
return;
}
}
map { $$_ } @{$ref->{values}};
}
package main;
use File::Spec::Unix;
my $obj = Search::ByPrefix->new;
sub make_key {
[File::Spec::Unix->splitdir($_[0])];
}
foreach my $dir (
qw(
/home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members
/home/user1/tmp2/coven/members
/home/user2/tmp2/coven/members
)
) {
$obj->add(make_key($dir), $dir);
}
# Finds the common directories
say for $obj->search(make_key('/home/user1/tmp'));