title: To replace a string and append a string in perl in 1 file
body: <p>I want to replace a line in my file and after replacing it I want to append another line. As you can see here, I have to open and close files for 2 times. Can I do it by opening a file only once? Thanks  </p>
  
  <pre><code>  use strict;
    use warnings;
  
     open(FILE,"tmp1.txt") || die "Can't open file: $!";
     undef $/;
     my $file = &lt;FILE&gt;;
     my @lines = &lt;FILE&gt;;
     my @newlines;
     for each(@lines) {
       $_ =~ s/hello/hi/g;
       push(@newlines,$_);
      }
     close(FILE);
     open(FILE, "&gt; tmp1.txt ") || die "File not found";
     print FILE @newlines;
    close(FILE);
  
    open(FILE,"tmp1.txt") || die "Can't open file: $!";
    undef $/;
    my $file = &lt;FILE&gt;;
    my @lines = &lt;FILE&gt;;
    my $first_line = "hi";
    my $second_line = "sun";
    my $insert = "good morning";
  
  
    $file =~ s/\Q$first_line\E\n\Q$second_line\E/$first_line\n$insert\n$second_line/;
  
  
    open(OUTPUT,"&gt; tmp3.txt") || die "Can't open file: $!";
    print OUTPUT $file;
    close(OUTPUT);
  </code></pre>