search_by_prefix.pl 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 29 July 2016
  5. # Website: https://github.com/trizen
  6. # Analyzes a list of strings and returns those that have a certain prefix
  7. package Search::ByPrefix;
  8. use 5.014;
  9. use strict;
  10. use warnings;
  11. sub new {
  12. my ($class, %opt) = @_;
  13. bless {table => $opt{table} // {}}, $class;
  14. }
  15. sub add {
  16. my ($self, $key, $value) = @_;
  17. my $ref = $self->{table};
  18. foreach my $item (@$key) {
  19. $ref = $ref->{$item} //= {};
  20. push @{$ref->{values}}, \$value;
  21. }
  22. $self;
  23. }
  24. sub search {
  25. my ($self, $pattern) = @_;
  26. my $ref = $self->{table};
  27. foreach my $item (@$pattern) {
  28. if (exists $ref->{$item}) {
  29. $ref = $ref->{$item};
  30. }
  31. else {
  32. return;
  33. }
  34. }
  35. map { $$_ } @{$ref->{values}};
  36. }
  37. package main;
  38. use File::Spec::Unix;
  39. my $obj = Search::ByPrefix->new;
  40. sub make_key {
  41. [File::Spec::Unix->splitdir($_[0])];
  42. }
  43. foreach my $dir (
  44. qw(
  45. /home/user1/tmp/coverage/test
  46. /home/user1/tmp/covert/operator
  47. /home/user1/tmp/coven/members
  48. /home/user1/tmp2/coven/members
  49. /home/user2/tmp2/coven/members
  50. )
  51. ) {
  52. $obj->add(make_key($dir), $dir);
  53. }
  54. # Finds the common directories
  55. say for $obj->search(make_key('/home/user1/tmp'));