Replacing some string in a text file shifts the remaining text to next line

Viewed 51

I am trying to replace a string in a text file using Perl script. The value gets replaced successfully. However, it shifts the remaining text of the line to the next line. I want the line to be intact as before. Can someone help?

sample_file_dml has the below text in it:

seq_no,1,1,GET,xyz
seq_no,1,2,PUT,xyz

I want to replace seq_no in each line with the value of variable seq_no_value. This value is obtained through some calculations in my code (for example - 9999).

Expected output:

9999,1,1,GET,xyz
9999,1,2,PUT,xyz

But, I am getting the below output:

9999
,1,1,GET,xyz
9999
,1,2,PUT,xyz

Code snippet used:

        open my $IN, '<', $sample_dml_file or die $!;
        open my $OUT, '>>', $new_dml_file or die $!;
        
        while (<$IN>) {
            s/\b(seq_no)\b/$seq_no_value/g;
            print {$OUT} $_;
        }
        close $OUT or die $!;
1 Answers

I believe $seq_no_value also has a newline character in it at the end (\n). You can remove it with chomp:

chomp $seq_no_value;

Perhaps you were reading lines of a file when you set the variable.

Here is a self-contained example:

use warnings;
use strict;

my $seq_no_value = "9999\n";
chomp $seq_no_value;
while (<DATA>) {
    s/\b(seq_no)\b/$seq_no_value/g;
    print $_;
}

__DATA__
seq_no,1,1,GET,xyz
seq_no,1,2,PUT,xyz

This outputs:

9999,1,1,GET,xyz
9999,1,2,PUT,xyz

If you comment out the chomp line, you get your original results.

Related