http://qs1969.pair.com?node_id=1184298

jnarayan81 has asked for the wisdom of the Perl Monks concerning the following question:

I have a matrix with human features (f1 .. f4)

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

I wanted to query with selected feature (f1 ..f4), and print the best match.

use strict; use warnings; my @array = (37,35,59,70); #Are in the same order as in matrix f1 f2 f +3 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)<abs(@$a[$mid+1]-$find) ? [$test] : $find <= @$a[$mid+1] ? [@$a[$mid+1]] : nearest([@$a[$mid+1 .. $ +size-1]])) : (abs($test-$find)<abs(@$a[$mid-1]-$find) ? [$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; }

I wrote script and it print followings; It seems nearest function does not work !!!

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

As you can see, I am opening and closing the matrix file four time, which would be really time consuming on long file.

Is there any other SMART way to achieve the best result? Thanks for you time.