6 use Digest::SHA1 qw(sha1_base64);
9 my $conf = {}; # configuration hashref
12 my %fps = (); # records matching each fingerprint (and the lead)
13 my @recs = (); # fingerprints belonging to each record
14 my %seen = (); # records we've already seen
15 my $lastscore = 0; # previous fingerprint's score
17 open FP, '<', $ARGV[0] or die "Can't open input file: $!\n";
19 print "Loading and ranking fingerprints\n";
21 my @fields = split "\t", $_;
22 my $fp = populate_fingerprint(@fields);
23 rank_fingerprint($fp);
25 print "Writing matchset to disk\n";
30 sub populate_fingerprint {
32 my %fp = (); # zero fingerprint hash each time thru
34 # populate fp hash -- first the simple data
35 $fp{compact} = shift @fields;
36 $fp{json} = shift @fields;
37 $fp{id} = shift @fields;
38 # then smash everything else together, remove non-Roman characters, and
39 # generate a SHA1 hash to represent it
40 my $stripped = join('', @fields);
41 $stripped =~ s/[^A-Za-z0-9]//g;
42 $fp{sha1} = sha1_base64($stripped);
44 # make sure file is sorted properly
45 if ($lastscore and ($fp{compact} > $lastscore)) {
46 print "Input file is sorted improperly or unsorted.\n";
47 die "Sort descending (sort -r) and rerun this script.\n";
49 $lastscore = $fp{compact};
55 sub rank_fingerprint {
58 my $sha1 = $fp->{sha1};
61 # only process records which haven't already been seen
62 unless (defined $seen{$id}) {
63 unless (defined $fps{$sha1}) {
64 # haven't seen this fp before. create a new listref to hold subs
65 # and stow the hash of the fingerprint that we're lead of
67 push @recs, {id => $id, sha1 => $sha1};
69 # have seen this fp. push record id onto matchlist
70 push @{ $fps{$sha1} }, $id;
79 Writes out a 2-column file of lead and subordinate records.
85 open OUT, '>', $conf->{output}
86 or die "Can't open ", $conf->{output}, "$!\n";
88 print OUT $rec->{id}, "\t$_\n"
89 for ( @{ $fps{ $rec->{sha1} } } );
97 # set mode on existing filehandles
98 binmode(STDIN, ':utf8');
100 my $rc = GetOptions( $c,
104 show_help() unless $rc;
105 show_help() if ($c->{help});
107 my @keys = keys %{$c};
108 show_help() unless (@ARGV and @keys);
109 for my $key ('output')
110 { push @missing, $key unless $c->{$key} }
112 print "Required option: ", join(', ', @missing), " missing!\n";
119 Usage is: compress_fingerprints -o OUTPUTFILE INPUTFILE