Perl print function adding unwanted newlines to va

2019-08-12 16:09发布

问题:

I thought this would be simple enough. I have two arrays, and I want to print a sentence with numbers from these arrays into a file. I tried this:

chomp $array1[$x];
chomp $array2[$x];
print FILE "Number1: $array1[$x] \& Number2: $array2[$x] Some Words\n";

Which gives me:

Number1: 0
 & Number2: 87.3
 Some Words

(Numbers here are just examples.)

Any idea why this is happening? I've tried using

$array1[$x] =~ s/\n//g;
$array2[$x] =~ s/\n//g;

as well, but it hasn't fixed anything. Also, if I explicitly place these extra newlines in, like so:

print FILE "Number1: $array1[$x]\n \& Number2: $array2[$x]\n Some Words\n"

I get the same output, so the unwanted newlines aren't being added anymore. Why?

回答1:

As the file was created on Windows it likely has CRLF (i.e. \r\n) line termination, not just LF. chomp will by default only remove the LF.

This line will remove LF with an optional preceding CR:

$array1[$x] =~ s/\r?\n//;

Alternatively, change $/ (the default "input record separator") to contain \r\n, at which point chomp should correctly strip both.