繁体   English   中英

Perl chomp不会删除换行符

[英]Perl chomp doesn't remove the newline

我想从文件的第一行中读取一个字符串,然后在控制台中重复n次重复,其中n被指定为文件中的第二行。

我觉得简单吗?

#!/usr/bin/perl
open(INPUT, "input.txt");
chomp($text = <INPUT>);
chomp($repetitions = <INPUT>);
print $text x $repetitions;

其中input.txt如下

Hello
3

我期望输出是

HelloHelloHello

但是,尽管使用了chomp但单词chomp新行分隔。

Hello
Hello
Hello

您可以在以下Perl小提琴上尝试一下CompileOnline

奇怪的是,如果代码如下:

#!/usr/bin/perl
open(INPUT, "input.txt");
chomp($text = <INPUT>);
print $text x 3;

它将正常工作并显示

HelloHelloHello

我是在误解什么,还是在线编译器有问题?

您的行尾出现问题; chomp$text删除$/尾随char / string,并且会因平台而异。 不过,您可以选择使用正则表达式从字符串中删除任何结尾的空格,

open(my $INPUT, "<", "input.txt");
my $text = <$INPUT>;
my $repetitions = <$INPUT>;

s/\s+\z// for $text, $repetitions;
print $text x $repetitions;

我正在使用在线的Perl编辑器/编译器,如初始帖子http://compileonline.com/execute_perl_online.php所述。

输出的原因是,字符串Hello\\rHello\\rHello\\r在html中的解释不同( \\ r类似于line break ),而在控制台中\\r将光标返回到当前行的开头。

暂无
暂无

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

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