Perl print function adding unwanted newlines to variables

安稳与你 提交于 2019-12-13 00:33:20

问题


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.



来源:https://stackoverflow.com/questions/12757404/perl-print-function-adding-unwanted-newlines-to-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!