Last active
May 22, 2017 20:38
-
-
Save alexpreynolds/9fc6f75c9516f30233f930077b3639f4 to your computer and use it in GitHub Desktop.
Intersect two hash tables in Perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: