A slightly different approach than that suggested by igelkott: first read in your first file and store the keys in a hash (of arrays). Then read the second file and store the sequence in the hash if the hash has a matching key.
use strict; use warnings; use Data::Dumper; use Fatal qw[open]; my %key; open my $data, '<', 'data.txt'; while(<$data>) { chomp; $key{$_} = []; } my %line; open my $all, '<', 'all.txt'; while(<$all>) { chomp; $line{key} = $_; $line{seq} = <$all>; # read the sequence chomp $line{seq}; my ($key) = ($line{key} =~ /(Contig\d*)/); if(exists $key{$key}) { push @{$key{$key}}, $line{seq}; } } print Dumper(\%key) ."\n";
with data.txt and all.txt as given this produces:
$VAR1 = { 'Contig25396' => [ 'GGGATCTTTGGACGAAGGGGGGAAAAAGATGTCAACTTTA +AGCATTCCAC CAATGCTTACTTCCCCTAGAGATGATGCCATTCAACTGTACAAGGCTTTC AAGGGAT +TTGGATGTGACACTTCTGCAGTAATCCATATCTTAGCTCGTCG' ], 'Contig25381' => [ 'GGACGAGATTTAACGACATCCATAAGCAACTCTGCTAATC +ATTCGATCTG CTTGGAGGTGTTTTTCCCCCATTTCCCTTAACCATGTCTCAGACTGTGGT' ], 'Contig25469' => [ 'GGCTCTCTACCTATCTGTCTCTCTCTACCTCTCTCTCCTT +TCACGCACAC' ] };
Update: amended version per Re^2: compare a list from one file with another text file

use strict; use warnings; use Data::Dumper; use Fatal qw[open]; my %key; open my $data, '<', 'data.txt'; while(<$data>) { chomp; $key{$_} = 1; } my %line; open my $all, '<', 'all.txt'; open my $out, '>', 'requery.txt'; while(<$all>) { chomp; $line{key} = $_; $line{seq} = <$all>; # read the sequence chomp $line{seq}; my ($key) = ($line{key} =~ /(Contig\d*)/); if(exists $key{$key}) { print $out join("\n", $line{key}, $line{seq}) . "\n"; } }


In reply to Re: compare a list from one file with another text file by Arunbear
in thread compare a list from one file with another text file by sm2004

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.