【问题标题】:Perl: Import text, containing ÅÄÖ, from filePerl:从文件中导入包含 ÅÄÖ 的文本
【发布时间】:2015-01-22 08:16:51
【问题描述】:

我在这里最终想要实现的是将文件中的所有小写字符转换为大写并将它们写入终端。

use utf8;
binmode STDOUT, ":utf8";

$text = "ABCÅÄÖ\n";

$text =~ tr/A-Ö/a-ö/;
print $text;

输出:

abcåäö

正如预期的那样。

但是当我尝试从文件中导入相同的文本时,它会变得很疯狂。

use utf8;
binmode STDOUT, ":utf8";

open FILE, $filename or die "An error occurred while reading the file: $!";
$text = join '', <FILE>;
close FILE or die "An error occurred while closing the file: $!";

$text =~ tr/A-Ö/a-ö/;
print $text;

输出

ABCÃÃÃ

我假设导入的文本没有正确编码。有人知道如何在导入文本时对其进行编码吗?

提前致谢。

杰克

【问题讨论】:

    标签: perl file encoding io


    【解决方案1】:

    你没有告诉 Perl 解码文件。

    use strict;
    use warnings;
    
    use utf8;                             # Source code is UTF-8.
    use open ':std', ':encoding(UTF-8)';  # Terminal and files are UTF-8.
    
    my $qfn = ...;
    
    open(my $fh, '<', $qfn)
       or die("Can't open file $qfn: $!\n");
    
    my $text = do { local $/; <$fh> };
    print(lc($text));
    

    【讨论】:

    • 嗯,依赖$text =~ tr/A-Ö/a-ö/ 是不安全的。使用lc($text)$text =~ s/([A-ZÅÄÖ])/\L$1/g。我进行了许多其他改进(词汇而不是全局,3-arg 打开,错误消息中包含文件名,...)
    【解决方案2】:

    只需告诉 Perl 文件的编码方式:

    open FILE, '<:utf8', $filename or die $!;
    

    或者,如果你想检查编码,使用

    open FILE, '<:encoding(UTF-8)', $filename or die $!;
    

    【讨论】:

    • 奇...我用这个方法导入没问题(IE可以很好的打印文本),但是翻译的时候ÅÄ和Ö还是乱码。
    • @JackPettersson:试试lc 而不是tr
    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 2015-12-24
    • 2011-07-28
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多