Skip to content

Instantly share code, notes, and snippets.

@alexpreynolds
Last active May 22, 2017 20:38
Show Gist options
  • Save alexpreynolds/9fc6f75c9516f30233f930077b3639f4 to your computer and use it in GitHub Desktop.
Save alexpreynolds/9fc6f75c9516f30233f930077b3639f4 to your computer and use it in GitHub Desktop.
Intersect two hash tables in Perl
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
my $fileA = undef;
my $fileB = undef;
my $result = GetOptions("fileA=s" => \$fileA, "fileB=s" => \$fileB);
sub convert_file_into_ht {
my ($fn) = @_;
open(my $fh, '<:encoding(UTF-8)', $fn) or die "$!\n";
my $line = <$fh>;
my $ht = undef;
while(<$fh>) {
chomp;
my ($location, $position) = split("\t", $_);
if (! exists $ht->{$location}) {
$ht->{$location} = [];
}
push(@{$ht->{$location}}, int($position));
}
close($fh);
return \%{$ht};
}
my $aRef = convert_file_into_ht($fileA);
my $bRef = convert_file_into_ht($fileB);
print("LOCATION\tPOSITION\n");
foreach my $key (keys %{$aRef}) {
my $aVals = $aRef->{$key};
if (exists $bRef->{$key}) {
my $bVals = $bRef->{$key};
my $intersection = undef;
for (@{$aVals}) {
if ($_ ~~ @{$bVals}) {
push(@{$intersection}, $_);
}
}
if (defined $intersection) {
for (@{$intersection}) {
print("$key\t$_\n");
}
}
}
}
@alexpreynolds
Copy link
Author

Usage:

$ intersect.pl --fileA="A.txt" --fileB="B.txt" > answer.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment