【问题标题】:Perl chomp doesn't remove the newlinePerl chomp 不会删除换行符
【发布时间】:2014-05-03 17:47:36
【问题描述】:

我想从文件的第一行读取一个字符串,然后在控制台中重复 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,但单词是换行符。

Hello
Hello
Hello

你可以试试下面的 Perl fiddle CompileOnline

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

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

它可以正常工作并显示

HelloHelloHello

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

【问题讨论】:

  • 这看起来像是行尾问题...您在哪个平台上工作?
  • hexdump -C input.txtperl -e 'print $/' | hexdump -C 是什么?
  • 我正在使用初始帖子compileonline.com/execute_perl_online.php中提到的在线 Perl 编辑器/编译器
  • hexdump 结果为:00000000 48 65 6c 6c 6f 0d 0a 33 |Hello..3| 00000008

标签: perl chomp


【解决方案1】:

您对行尾有疑问; chomp$text 中删除$/ 的尾随字符/字符串,这可能因平台而异。但是,您可以选择使用正则表达式从字符串中删除任何尾随空格,

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

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

我正在使用最初的帖子http://compileonline.com/execute_perl_online.php 中提到的在线 Perl 编辑器/编译器

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

【讨论】:

  • 所以问题出在平台上,而不是代码上。听起来不错 !正则表达式+1。我会标记并解决!谢谢
  • 这并不能解释为什么print $text x 3 有效,但print $text x $repetitions 无效
  • 你是对的@Borodin,这仍然是一个悬而未决的问题,所以我将删除标记作为答案标志,直到从后者回答为什么它有这种行为。
  • @mpapec:\z 是什么?
  • @Borodin 我猜 mpapec 提到了 HTML,因为提问者使用了在线 Perl 编译器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
相关资源
最近更新 更多