Name f1 f2 f3 f4
africa1 18 1 48 23
usa2 48 23 60 23
africa2 17 3 49 25
africa3 20 6 52 30
usa1 55 20 56 25
china1 35 37 55 87
china2 40 33 50 73
####
use strict;
use warnings;
my @array = (37,35,59,70); #Are in the same order as in matrix f1 f2 f3 f4
for(my $i = 1; $i <= 4; $i++) {
my %hash; my @allval;
my $fh=read_fh($ARGV[0]); #Matrix file here
while(<$fh>) {
chomp; next if $. ==1; #Ignore header
my @val = split('\t', $_);
$hash{$val[0]}=$val[$i];
push (@allval, $val[$i]);
}
close $fh;
#foreach (sort keys %hash) { print "$_ : $hash{$_}\n";}
my @allval_sorted = sort {$a <=> $b} @allval;
my $find =$array[$i-1];
#my $nearest = @{nearest(\@allval_sorted)}[0];
use List::Util 'max'; my $selected = max grep { $find >= $_ } @allval_sorted; my $nearest=$selected;
my @keys = grep { $hash{$_} == $nearest } keys %hash;
print "nearest to $find in array is: $nearest and name is $keys[0]\n";
undef @allval; undef %hash;
sub nearest {
my ($a) = @_;
my $size = @$a;
return $a if $size == 1;
my $mid = int(($size-1) / 2);
my $test = @$a[$mid];
return $test <= $find ?
(abs($test-$find)= @$a[$mid-1] ? [@$a[$mid-1]] : nearest([@$a[0 .. $mid]]));
}
}
#Open and Read a file
sub read_fh {
my $filename = shift @_;
my $filehandle;
if ($filename =~ /gz$/) {
open $filehandle, "gunzip -dc $filename |" or die $!;
}
else {
open $filehandle, "<$filename" or die $!;
}
return $filehandle;
}
##
##
WITH NEAREST sub
jitendra@jitendra-Aspire-S3-391[test] perl testMAT.pl mat.txt [10:17PM]
nearest to 37 in array is: 35 and name is china1
nearest to 35 in array is: 37 and name is china1
nearest to 59 in array is: 48 and name is africa1
nearest to 70 in array is: 30 and name is africa3
WITH use List::Util 'max'
jitendra@jitendra-Aspire-S3-391[test] perl testMAT.pl mat.txt [10:19PM]
nearest to 37 in array is: 35 and name is china1
nearest to 35 in array is: 33 and name is china2
nearest to 59 in array is: 56 and name is usa1
nearest to 70 in array is: 30 and name is africa3