是否有任何打开的问题(我的$ f,'<:encoding(UTF-8)',$ n)

时间:2016-07-26 12:55:15

标签: perl

我遇到的问题是我无法以适合Stackoverflow的方式重现,尽管它在我的生产环境中可以重现。

问题出现在Perl脚本中,其中包括迭代文件,如下所示:

abc-4-9|free text, possibly containing non-ascii characters|
cde-3-8|hällo wörld|
# comment

xyz-9-1|and so on|
qrs-2-8|and so forth|

我可以使用此Perl脚本验证文件的正确性:

use warnings;
use strict;

open (my $f, '<:encoding(UTF-8)', 'c:\path\to\file') or die "$!";

while (my $s = <$f>) {
  chomp($s);
  next unless $s;
  next if $s =~ m/^#/;
  $s =~ m!(\w+)-(\d+)-(\d+)\|([^|]*)\|! or die "\n>$s<\n didn't match on line $.";
}

print "Ok\n";
close $f;

当我运行此脚本时,它不会在第10行死亡,因此会打印Ok

现在,我在一个巨大的Perl脚本中使用了相同的构造(因此对于Stackoverflow来说是无法生成的),它将在输入文件的第2199行死掉。

如果我将第一行(与第2199行完全无关)改为

 www-1-1|A line with some words|

 www-1-1|x|

脚本将处理第2199行(但稍后失败)。

有趣的是,当我改变

时引入了这种行为
open (my $f, '<', 'c:\path\to\file') or die "$!";

open (my $f, '<:encoding(UTF-8)', 'c:\path\to\file') or die "$!";

如果没有:encoding(UTF-8)指令,脚本不会失败。当然,我需要编码指令,因为该文件包含非ascii字符。

BTW,同样的脚本在Linux上没有问题。

在Windows上,它失败了,我使用Strawberry Perl 5.24

1 个答案:

答案 0 :(得分:2)

我没有完整正确的解释为什么这是必要的,但您可以尝试打开文件

'<:unix:encoding(UTF-8)'

这可能与我的问题相关&#34; Why is CRLF set for the unix layer on Windows?&#34;当我试图找出我最终没搞清楚的东西时,我注意到了。