【问题标题】:perl special char windowsperl 特殊字符窗口
【发布时间】:2015-02-02 19:15:29
【问题描述】:

我尝试在 ma perl 控制台应用程序的输出中使用德语特殊字符:öäüßÖÄÜ,但我失败了。这是一个带有活动代码页 850 的德国 win7 系统。

#!/usr/bin/perl 
use warnings;
use strict;

binmode(STDOUT , ":encoding(cp437)" )  if $^O eq 'MSWin32';
#binmode(STDOUT , ":encoding(cp850)" )  if $^O eq 'MSWin32';
#binmode(STDOUT , ":encoding(cp1252)" ) if $^O eq 'MSWin32';

my @sp_chars = qw/ä ö ü ß Ä Ö Ü/;

foreach my $sp_char ( @sp_chars ) {
  print "$sp_char\n";
}

我收到如下错误:

"\x{009f}" does not map to cp1252 at umlaute.pl line 12.

"\x{009f}" does not map to cp850 at umlaute.pl line 12.

"\x{00c3}" does not map to cp437 at umlaute.pl line 12.

如何获得正确的输出?

【问题讨论】:

    标签: perl codepages binmode


    【解决方案1】:

    在你的源码中使用utf8字符并使用IO层进行编码时,你应该在perl解析器中开启utf8:

    use utf8; 
    
    my $encoding = $^O eq 'MSWin32' ? 'cp850' : 'utf8';
    binmode(STDOUT, ":encoding($encoding)" );
    
    print "$_\n" for qw/ä ö ü ß Ä Ö Ü/;
    

    【讨论】:

    • 嗨,Ben,“来自您的源代码”是我需要的提示。我错过了重点,notepad++ 设置为 utf8。非常感谢你!皮特
    • @Pete:正确的解决方案是通过在源文件中添加use utf8 作为第一条语句来告诉 Perl 源是UTF-8 格式。现在使用代码页 850(DOS 拉丁语 1)是不寻常的,因为 ISO-8859-1(代码页 1252,除了一些琐事)已在很大程度上取代了它。您可能会发现在整个过程中使用 UTF-8 更简单,它通过 Windows 代码页 65001 得到支持。
    • 对,如果您打算在程序中的任何位置使用编码层,则必须一致地表示数据。将所有内容都视为字节通常更容易,因此我通常不打开 utf8,即使源中有 utf8 字符也是如此。但我会更新答案,因为它是更现代的方法:)
    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-07-11
    相关资源
    最近更新 更多