title: Extract a part of string using a pattern, start with a value of variable in Perl
body: <p>I am very new in Perl and I am confused how to do this task. I have two files:</p>
  
  <ol>
  <li>Seq.txt, which contains many sequences (database)</li>
  <li>PID.txt, which contains only IDs (query) for some sequences which I need to extract from Seq.txt file.</li>
  </ol>
  
  <p>Here I am giving a small part of my both files:</p>
  
  <p>Seq.txt contains: </p>
  
  <pre><code>'&gt;' SCO0700,  probable ABC transporter protein, ATP-binding component. 
  MASSMEKPLDHRYRGEHPIRTLVYLFRADRRRLAGAVAVFTVKHSPIWLLPLVTAAIVDT
  VVQHGPITDLWTSTGLIMFILVVNYPLHLLYVRLLYGSVRRMGTALRSALCTRMQQLSIG  
  '&gt;' SCO0755, putative ABC transporter 797720:799942 forward MW:79858
  VSTAQETRGRRRAAPPRRSVPKSRARTVRTPTVLQMEAVECGAASLAMVLGHYGRHVPLE
  ELRIACGVSRDGSRASNLLKAARSYGFTAKGMQMDLAALAEVTAPAILFWEFNHYVVYDG  
  '&gt;' SCO2305,putative ABC transporter ATP-binding subunit 2474063:2474989 forward MW:32345
  MRPTEGTTPAVAFTGAAKAYGDVRAVDGVDLRIGCGETVALLGRNGAGKSTTIALLLGLC
  PPDAGTVELFGGPAERAVRAGRVGAMLQEARAVPRVTVGELVAFVAGRYPAPMPVGQALE   
  '&gt;' SCO1144, putative ABC transporter ATP-binding protein 1202480:1204282 reverse MW:64637
  MHPDRESAWTAPADAVEQPRQVRRILKLFRPYRGRLAVVGLLVGAASLVSVATPFLLKEI
  LDVAIPEGRTGLLSLLALGMIFGAVLTSVFGVLQTLISTTVGQRVMHDLRTAVYGRLQQM  
  '&gt;' SCO1148, putative ABC transporter 1207772:1209553 forward MW:63721
  MIGVAPPSYDPAAPTTANTLPVGARPTVRAYVGELLRRHRRAFLFLVTVNTVAVIASMAG
  PYLLGGLVERVSDDARELRLGLTATLFVLALVVQAVFVREVRLRGAVLGERMLADLREDF
  </code></pre>
  
  <p>PID.txt contains:   </p>
  
  <pre><code>SCO0755  
  SCO1144
  </code></pre>
  
  <p>Code I have written:</p>
  
  <pre><code>open (PID, 'PID.txt');  
  my @PID = '&lt;'PID'&gt;';  
  close(PID);  
  open (MSD, 'Seq.txt');  
  my @MSD = '&lt;'MSD'&gt;';    
  close(MSD);  
  chomp(@MSD);  
  my $MSD=join (' ', @MSD);  
  print "$MSD \n";  
  for ($i = 0; $i&lt;=2; $i++) {  
    my $a=$PID[$i];  
    if ($MSD =~ m/$a(.*?)&gt;/)  # "&gt;" end of the string  
    {  
      print "$1 \n";  
      $output= "&gt;".$a.$1;  
      print $output;  
      open (MYFILE, '&gt;&gt;data.txt');  
      print MYFILE "$output\n";    
      close (MYFILE);    
    }  
  }
  </code></pre>
  
  <p>Why is it not recognizing <code>$a</code>? If I put [<strong>$a</strong>], then the binding operator recognize <code>$a</code> but do not return my desired sequence (with ID stored in <code>$a</code>), instead it returns the very first sequence.</p>
  
  <p>The result I expect is:  </p>
  
  <pre><code>'&gt;' SCO0755, putative ABC transporter 797720:799942 forward MW:79858
  VSTAQETRGRRRAAPPRRSVPKSRARTVRTPTVLQMEAVECGAASLAMVLGHYGRHVPLE
  ELRIACGVSRDGSRASNLLKAARSYGFTAKGMQMDLAALAEVTAPAILFWEFNHYVVYDG  
  '&gt;' SCO1144, putative ABC transporter ATP-binding protein 1202480:1204282 reverse MW:64637
  MHPDRESAWTAPADAVEQPRQVRRILKLFRPYRGRLAVVGLLVGAASLVSVATPFLLKEI
  LDVAIPEGRTGLLSLLALGMIFGAVLTSVFGVLQTLISTTVGQRVMHDLRTAVYGRLQQM
  </code></pre>