Perl grep two arrays -
i have 1 array filled short strings (@pos), , second larger array (@exome). want search second array match strings first. goal print lines @exome have match
im using perl have far
#!/usr/bin/perl use strict; use warnings; $pos = $argv[0]; $exome = $argv[1]; open (f, "$pos") || die "could not open $pos: $!\n"; @pos = <f>; close f; open (f, "$exome") || die "could not open $exome: $!\n"; @exome = <f>; close f; foreach (@pos) { @out = grep(/$_/, @exome); print @out }
i thought @ikegami has given out quite answer, but, seems mistakes in array print...maybe @user2249959 wants @exome array print... core code needed no more 2 lines:
my $grep_pos = join '|', @pos; @matched_results = grep { /$grep_pos/ } @exome;
well, can print out @ second line, there won't have blank space between elements in array. 2 foreach loops doesn't perl, in own opinion...
p.s. added 3 points pay attention
1. careful of invisible "\n" or "\r\n"
2. careful of white space @ beginning , ending of each string.
can solve above 2 points simple codes, example:
map { chomp; s/^\s*|\s*$// } @pos;
this delete "\n"(if have), , white spaces in front or @ end(if assume meaningless). before grep
3. more important! careful of blank lines in @pos array file!
if file looks this:
pos_1 pos_2 <---- totally blank pos_3
if still join lines '|', become 'pos_1|pos_2||pos_3', means in @exome match. (because of '||')
chomp or s/// won't help, got jump line yourself
careful :)
Comments
Post a Comment