Perl打印功能向变量添加不需要的换行符 [英] Perl print function adding unwanted newlines to variables
问题描述
我认为这很简单.我有两个数组,我想将这些数组中带有数字的句子打印到文件中.我试过了:
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";
哪个给我:
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?
推荐答案
在Windows上创建文件时,它可能具有CRLF
(即\r\n
)行终止,而不仅仅是LF
. chomp
默认情况下只会删除LF
.
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
.
此行将删除LF
,并在CR
之前添加可选:
This line will remove LF
with an optional preceding CR
:
$array1[$x] =~ s/\r?\n//;
或者,将$/
(默认为输入记录分隔符")更改为包含\r\n
,此时chomp
应该正确地将两者都剥离.
Alternatively, change $/
(the default "input record separator") to contain \r\n
, at which point chomp
should correctly strip both.
这篇关于Perl打印功能向变量添加不需要的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!