Oligo has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
I'm trying to master the art of searching with hashes. I have a file with a list of search terms (one line = one term):
J00153:42:HC5NCBBXX:6:1101:10896:14959 J00153:42:HC5NCBBXX:6:1101:10896:14959 J00153:42:HC5NCBBXX:6:1101:26616:20709 J00153:42:HC5NCBBXX:6:1101:27549:19935
...and a master file I want to search for those terms in (again, one line per record):
J00153:42:HC5NCBBXX:6:1101:10896:14959 99 gnl|Btau_4.6.1|chr16 + 72729218 1 12M J00153:42:HC5NCBBXX:6:1101:27549:19935 83 gnl|Btau_4.6.1|chr8 + 49556412 1 7M
I started by opening the query file and reading each line into an array. Then while-ing through the master file, returning matching lines where the array elements match the relevant part of the master file:
# Open query file and read into array $queryfile = $ARGV[0]; open (QUERYFILE, $queryfile) or die "Cannot open query file\n"; @queries = <QUERYFILE>; close QUERYFILE; # Open main file $mainfile = $ARGV[1]; open (MAINFILE, $mainfile) or die "Cannot open searchable file\n"; # Search through main file while ($inline = <MAINFILE>) { @split = split /\t/, $inline; $ID = $split[0]; if (grep /$ID/, @queries) { print $inline; } else { } } exit;
This works fine, but the files are huge and the code takes an age to run. So, I tried converting the array to a hash (array elements = hash keys, values all = 1) but I can't seem to get the pattern matching syntax right; the code runs much faster but nothing comes back. So far I have:
# Open query file and read into array $queryfile = $ARGV[0]; open (QUERYFILE, $queryfile) or die "Cannot open query file\n"; @queries = <QUERYFILE>; close QUERYFILE; # Convert array to hash %hash = map {$_ => 1} @queries; # Open main file $mainfile = $ARGV[1]; open (MAINFILE, $mainfile) or die "Cannot open searchable file\n"; # Search through main file while ($inline = <MAINFILE>) { @split = split /\t/, $inline; $ID = $split[0]; if (defined $hash{$ID}) { print $inline; } else { } } exit;
Any Perly wisodom greatly appreciated!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Hash searching
by Eily (Monsignor) on Aug 24, 2016 at 11:47 UTC | |
|
Re: Hash searching
by kcott (Archbishop) on Aug 24, 2016 at 16:03 UTC | |
by Eily (Monsignor) on Aug 26, 2016 at 14:23 UTC | |
by kcott (Archbishop) on Aug 31, 2016 at 04:56 UTC | |
by Oligo (Novice) on Aug 25, 2016 at 12:00 UTC | |
by kcott (Archbishop) on Aug 26, 2016 at 11:48 UTC |