If I may, I'd like to offer just a few suggestions which may assist your efforts:

Give the above items, consider the following refactoring:

use strict; use warnings; my $posfile = 'posfile.txt'; my $pos_two = 'pos_two.txt'; my @isos20 = qw/these are the array elements/; my %isos20 = map { $_ => 1 } @isos20; #open file to write filtered lines to open my $OUT2, '>', $pos_two or die "cannot open $pos_two: $!"; #open file to filter open my $IN2, '<', $posfile or die "cannot open $posfile: $!"; while (<$IN2>) { my $comp = ( split /,/ )[0]; print $OUT2 $_ if $isos20{$comp}; } close $IN2; close $OUT2;

Notice that there are fewer instructions within the while loop. Instead of assigning the value of Perl's default scalar $_ to $line, just operate on $_.

The split gets the ID from the file's string by creating a list of string elements and taking the zeroth element of that list. The $isos20{$comp} notation 'looks' for that ID within the hash (constructed using map above), and prints the line to the output file if it's in the hash.

Why use a hash instead of grepping the array for a match? Using a hash is a much faster, more efficient way of detecting a match, in this case. For each line, the entire array is traversed by grep to find a possible match. However, a hash has a very efficient look-up algorithm, so will work better--significantly so, if the array is quite large.

Hope this helps!


In reply to Re: grep of readline matching more lines than elements in array by Kenosis
in thread grep of readline matching more lines than elements in array by bdorsey

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.