while ($line = ){ if($line =~ m/$agent/){ $line = $collect; #this line will be replaced by the $collect line in the file OUT } elsif ( $line =~ m/best1collect/) { next; #this line will NOT appear in the file OUT, because you #don't reach the print command. If you want this line in #the OUT file, I suggest, you use a continue block. See at #the end. } elsif ($line =~ m/'syslogd'\)/){ my $newline = $. + 3; $newline = $bgs; print OUT "$newline\n"; # this line will appear in the OUT file , but have the # bgs line inserted before. } # all other lines will be copied. print OUT $line; print $line; } #### while ($line = ){ if($line =~ m/$agent/){ $line = $collect; } elsif ( $line =~ m/best1collect/) { next; } elsif ($line =~ m/'syslogd'\)/){ my $newline = $. + 3; $newline = $bgs; print OUT "$newline\n"; } } continue { print OUT $line; print $line; }