diff options
| author | E. Choroba <choroba@matfyz.cz> | 2019-09-08 20:51:25 +0200 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2019-09-08 20:51:25 +0200 |
| commit | ca09301b02d9c826d6c7d8f5072911e63c85e06c (patch) | |
| tree | c1798470e2fcc576da1602531abd5a6f9d5e9fe8 /challenge-024 | |
| parent | 2750b06bab227ae3598ea7a37c32a07b393db60b (diff) | |
| download | perlweeklychallenge-club-ca09301b02d9c826d6c7d8f5072911e63c85e06c.tar.gz perlweeklychallenge-club-ca09301b02d9c826d6c7d8f5072911e63c85e06c.tar.bz2 perlweeklychallenge-club-ca09301b02d9c826d6c7d8f5072911e63c85e06c.zip | |
Add solution to 024/2 (inverted index) by E. Choroba
Diffstat (limited to 'challenge-024')
| -rwxr-xr-x | challenge-024/e-choroba/perl5/ch-2.pl | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/challenge-024/e-choroba/perl5/ch-2.pl b/challenge-024/e-choroba/perl5/ch-2.pl new file mode 100755 index 0000000000..a8df8734f5 --- /dev/null +++ b/challenge-024/e-choroba/perl5/ch-2.pl @@ -0,0 +1,56 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw{ say }; +use Syntax::Construct qw{ // }; + +use Storable qw{ store retrieve }; + + +sub help { + say STDERR "Usage: $0 help"; + say STDERR " $0 create index doc1 doc2..."; + say STDERR " $0 search index term"; +} + +sub create { + my ($index_file, @documents) = @_; + my %index; + for my $document (@documents) { + warn $document; + open my $in, '<', $document or do { + warn "$document: $!"; + next + }; + while (<$in>) { + push @{ $index{$1}{$document} }, $. while /(\w+)/g; + } + } + store(\%index, $index_file); +} + +sub search { + my ($index_file, $term) = @_; + my %index = %{ retrieve($index_file) }; + for my $document (keys %{ $index{$term} }) { + say "$document: ", join ' ', @{ $index{$term}{$document} }; + } +} + +sub unknown { + help(); + die "Unknown action\n"; +} + +my $action = shift; + +my %dispatch = ( + help => \&help, + create => \&create, + search => \&search, +); + +my $run = $dispatch{$action} // \&unknown; + +$run->(@ARGV); + |
