in reply to extract values from file if greater than value
This only prints the values - not sure how you want to store in an array (as you mentioned).#!/usr/bin/perl use strict; use warnings; open my $fh1, '<', \<<EOF or die $!; 1 19002930 0.74 1 19002931 -0.12 EOF my %data; while (<$fh1>) { next if /CHR/; my ($chr, $bp, $min) = split; $data{$chr,$bp} = $min; } open my $fh2, '<', \<<EOF or die $!; 1 19002930 0.84 0.12 0.94 1 19002931 0 -.20 .12 EOF while (<$fh2>) { my ($chr, $bp, @rest) = split; if (defined(my $min = $data{$chr,$bp})) { print join(" ", $chr, $bp, grep $_ >= $min, @rest), "\n"; } }
Update: Added the 'defined' operator to the if statement so a 'min' value of '0' will be accepted. Without testing for defined, a '0' value would cause the if statement to be wrongly false.
Also, like Marshall's solution, the temporary files I created were just for this example. You would need to open your files in the normal way open my $fh1, '<', 'yourfilename' or die $!.
Update 2: Noting Marshall's comment on separating $data{"$chr$bp"} by a space to be safer, $data{"$chr $bp"}, I used the seldom used idiom $data{$chr,$bp} where a comma separated series of terms as the key to a hash are joined together by the '$SUBSCRIPT_SEPARATOR', $;.
Also, I'm wondering what the purpose of next if /CHR/; is in his code. It is hard to see whithout a better data sample for the file he is reading.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: extract values from file if greater than value
by Marshall (Canon) on Jun 16, 2016 at 04:23 UTC |