2

我无法从 perl 文件中读取西里尔字符。

文本文件用记事本编写,包含“абвгдежзийклмнопрстуфхцчшщъьюя”。这是我的代码:

#!/usr/bin/perl

use warnings;
use strict;

open FILE, "text.txt" or die $!;

while (<FILE>) {
    print $_;   
}

如果我使用 ANSI 编码保存文本文件,我得到:

рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·№■

如果我使用 UTF-8 编码保存它,并使用包 Encode 中的函数 decode('UTF-8', $_) ,我得到:

Wide character in print at test.pl line 11, <TEXT> line 1.

和一堆不可读的字符。

我在 Windows 7x64 中使用命令提示符

4

1 回答 1

5

您正在解码您的输入,但“忘记”对您的输出进行编码。

您的文件可能是使用cp1251编码的。

您的终端需要cp866

采用

use open ':std', ':encoding(cp866)';
use open IO => ':encoding(cp1251)';
open(my $FILE, '<', 'text.txt')
   or die $!;

或者

use open ':std', ':encoding(cp866)';
open(my $FILE, '<:encoding(cp1251)', 'text.txt')
   or die $!;

如果您保存为 UTF-8,请使用:encoding(UTF-8)而不是。:encoding(cp1251)

于 2013-02-02T16:00:48.290 回答