title: How to efficiently search/replace certain strings in a file in perl?
body: <p>My file looks like this:  </p>
  
  <pre><code>&lt;MAIN&gt;  
    &lt;SUB_MAIN&gt;one&lt;/SUB_MAIN&gt;  
    &lt;VER&gt;version#&lt;/VER&gt;  
    (OTHER STUFF...)  
    &lt;LOCATION&gt;PATH&lt;/LOCATION&gt;  
  &lt;/MAIN&gt;
  
  &lt;MAIN&gt;  
    &lt;SUB_MAIN&gt;two&lt;/SUB_MAIN&gt;  
    &lt;VER&gt;version#&lt;/VER&gt;  
    (OTHER STUFF...)  
    &lt;LOC&gt;PATH&lt;/LOC&gt;  
  &lt;/MAIN&gt;
  </code></pre>
  
  <p>What I want to do is to search for the value of <code>SUB_MAIN</code> lets say one, and if I find it then look for the value of <code>LOCATION</code>. Go to that location do some syncing get a new version from there and update the <code>VER</code> information. </p>
  
  <p>My current code has like three loops and is ugly. The skeleton is like this:  </p>
  
  <pre><code>$value = "one|two|three";
  
  # for each line in file
  while ($line &lt; @FileDat) {
  
      # see if it is a sub module?   
      if ( $line =~ /\&lt;SUB_MAIN\&gt;$value\&lt;\/SUB_MAIN\&gt;/ ) 
      {   
         $found_it = 0;
  
          while (!$found_it) 
          {       
              $lineNum++;     
              if ( $FileDat[$lineNum] =~ /\&lt;VER\&gt;\d+\&lt;\/VER\&gt;/ ) 
              {
                  $currIndex = $lineNum;
  
                  while(1)
                  {
                     $lineNum++;
                     if ( $FileDat[$lineNum] =~ /\&lt;LOC\&gt;(.+)\&lt;\/LOC\&gt;/ ) 
                      {   #DO SOME STUFF...
                          $found_it = 1;
                          last;
                      }
                  }               
                          #replace version #
                  $FileDat[$currIndex] = "    &lt;VER&gt;$latestChangeList&lt;/VER&gt;\n";
              }
          }
      }
      $lineNum++;
  }
  
  # write the modified array to new file
  print NEWCFGFILEPTR @FileDat;
  
  close(OPEN_FILES);
  </code></pre>
  
  <p>How can I make it better?<br>
  Thank you.</p>