[Solved] How do I replace a line in a file using Perl?


The only actual problem with your code was that you were printing the line to the new file in the wrong place in the loop. You need to print every line from the old file into the new file.

Having tidied your file a little and updated some of the idioms, I end up with this:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my $old_file="in.txt";
my $new_file="out.txt";

my $CD_VER = 'CD29';

open my $rf, '<', $old_file or die "Cannot open $old_file for reading.";
open my $wf, '>'. $new_file or die "Cannot open $new_file for writing.";

while ( <$rf> ) {
    if (/CODEDROP/ and /regular/) {
        s/regular/$CD_VER/ ;
    }
    print $wf $_;
}

close $rf;
close $wf;

2

solved How do I replace a line in a file using Perl?