title: Copy selected lines from one file and insert those lines in another file after selected line
body: <p>Here is my question let's say I have a file
  <code>file1.txt</code> with contents:</p>
  
  <pre><code>abc.. 
  def.. 
  ghi.. 
  def..
  </code></pre>
  
  <p>and second file <code>file2.txt</code> with contents:</p>
  
  <pre><code>xxx..
  yyy..
  zzz..
  </code></pre>
  
  <p>Now I want to copy all the line starting with "def" in <code>file1.txt</code> to <code>file2.txt</code> and append after "yyy..." line in <code>file2.txt</code></p>
  
  <h3>Expected Output:</h3>
  
  <pre><code>xxx...
  yyy...
  def...
  def...
  zzz...
  </code></pre>
  
  <p>I am pretty much new to perl, I've tried writing simple code for this but end up with output only appending at the end of file</p>
  
  <pre><code>#!/usr/local/bin/perl -w 
  use strict; 
  use warnings;
  use vars qw($filecontent $total);
  my $file1 = "file1.txt";
  open(FILE1, $file1) || die "couldn't open the file!";
  open(FILE2, '&gt;&gt;file2.txt') || die "couldn't open the file!";
    while($filecontent = &lt;FILE1&gt;){
      if ( $filecontent =~ /def/ ) {
        chomp($filecontent);
         print FILE2 $filecontent ."\n";
        #print FILE2 $filecontent ."\n" if $filecontent =~/yyy/;
      }  
    } 
   close (FILE1); 
   close (FILE2);
  </code></pre>
  
  <p>output of the perl program is</p>
  
  <pre><code>xxx...
  yyy...
  zzz...
  def...
  def...
  </code></pre>