Perl中奇怪的打印行为

时间:2013-11-24 07:25:51

标签: perl cygwin

我想从文件中读取一些数字到数组中,然后将它们作为语句的一部分打印出来。但我得到了一些奇怪的结果。文件list1.txt包含以下文本:

01
02
15
30
43
75
76

我想打印:

The number is: 01;
The number is: 02;
The number is: 15;
The number is: 30;
The number is: 43;
The number is: 75;
The number is: 76;

所以我编写了以下简单程序:

my @arr;
my $i = 0;
open(my $file_fh,"<","list1.txt") or die "Could not find specified file\n";
while (<$file_fh>) {
    $arr[$i] = $_;
    chomp($arr[$i]);
    $i++;
}

foreach my $num (@arr) {
    my $stmt = "The number is: ".$num."\;";
    print "$stmt\n";
}

但我得到的结果是:

;he number is: 01
;he number is: 02
;he number is: 15
;he number is: 30
;he number is: 43
;he number is: 75
;he number is: 76

我做错了什么?

2 个答案:

答案 0 :(得分:8)

您正在阅读的文件采用Windows格式,每行末尾都有CRLF。您的cygwin Perl配置为使用Linux行结尾,因此chomp仅删除结尾LF,使字符串值保留为尾随CR,这会导致分号覆盖输出的第一个字符。

答案 1 :(得分:2)

您正在使用unix(cygwin)系统上的Perl读取Windows文本文件(CRLF行结尾)。 Unix系统希望文本文件具有LF结尾。

修复方法是使用s/\s+\z//代替chomp

相关问题