简体   繁体   English

为什么Perl的印记会影响我的打印输出?

[英]Why is Perl's chomp affecting the output of my print?

It's been a couple months since I've been Perling, but I'm totally stuck on why this is happening... 我从Perling到现在已经几个月了,但是我完全不知道为什么会这样。

I'm on OSX, if it matters. 如果有问题,我在OSX上。

I'm trying to transform lines in a file like 我正在尝试转换文件中的行

08/03/2011 01:00 PDT,1.11

into stdout lines like 变成标准输出

XXX, 20120803, 0100, KWH, 0.2809, A, YYY

Since I'm reading a file, I want to chomp after each line is read in. However, when I chomp , I find my printing gets all messed up. 因为我读一个文件,我想chomp每一行中读取之后。然而,当我chomp ,我发现我的打印得乱七八糟。 When I don't chomp the printing is fine (except for the extra newline...). 当我不chomp ,打印效果很好(除了多余的换行符...)。 What's going on here? 这里发生了什么?

while(<SOURCE>) {
    chomp;
    my @tokens = split(' |,');     # @tokens now [08/03/2011, 01:00, PDT, 1.11]

    my $converted_date = convertDate($tokens[0]);
    my $converted_time = convertTime($tokens[1]);

print<<EOF;
$XXX, $converted_date, $converted_time, KWH, $tokens[3], A, YYY
EOF
}

With the chomp call in there, the output is all mixed up: 在其中存在chomp调用的情况下,所有输出混合在一起:

, A, YYY10803, 0100, KWH, 1.11

Without the chomp call in there, it's at least printing in the right order, but with the extra new line: 如果没有chomp调用,它至少会以正确的顺序进行打印,但要额外增加一行:

XXX, 20110803, 0100, KWH, 1.11
, A, YYY

Notice that with the chomp in there, it's like it overwrites the newline "on top of" the first line. 请注意,在其中插入了chomp之后,就好像它覆盖了第一行“顶部”的换行符。 I've added the $|=1; 我加了$|=1; autoflush, but don't know what else to do here. 自动刷新,但不知道在这里还要做什么。

Thoughts? 有什么想法吗? And thanks in advance.... 并预先感谢...。

The lines of your input ends with CR LF. 输入的行以CR LF结尾。 You're removing the LF only. 您仅删除LF。 A simple solution is to use the following instead of chomp : 一个简单的解决方案是使用以下代码代替chomp

s/\s+\z//;

You could also use the dos2unix command line tool to convert the files before passing them to Perl. 您还可以使用dos2unix命令行工具转换文件,然后再将其传递给Perl。

The problem is that you have DOS line-endings and are running on a Unix build of Perl. 问题是您有DOS行尾,并且在Perl的Unix版本上运行。

One solution to this is to use PerlIO::eol . 一种解决方案是使用PerlIO::eol You may have to install it but there is no need for a use line in the program. 您可能必须安装它,但是程序中不需要use线。

Then you can write 那你可以写

binmode ':raw:eol(LF)', $filehandle;

after which, regardless of the format or source of the file, the lines read will be terminated with the standard "\\n" . 之后,无论文件的格式或来源如何,读取的行都将以标准"\\n"终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM