在将Unicode字符串打印到Windows控制台*时遇到一个奇怪的问题。
考虑以下文本:
אני רוצה לישון
Intermediary
היא רוצה לישון
אתם, הם
Bye
Hello, world!
test
假设它在一个名为“file.txt”的文件中。
当我去*:“键入file.txt”时,它可以正常打印。但是从Perl程序打印时,如下所示:
use strict;
use warnings;
use Encode;
use 5.014;
use utf8;
use autodie;
use warnings qw< FATAL utf8 >;
use open qw< :std :utf8 >;
use feature qw< unicode_strings >;
use warnings 'all';
binmode STDOUT, ':utf8'; # output should be in UTF-8
my $word;
my @array = ( 'אני רוצה לישון', 'Intermediary',
'היא רוצה לישון', 'אתם, הם', 'Bye','Hello, world!', 'test');
foreach $word(@array) {
say $word;
}
每次都再次显示Unicode行(在本例中为希伯来语),部分中断,如下所示:
E:\My Documents\Technical\Perl>perl "hello unicode.pl"
אני רוצה לישון
לישון
�ן
Intermediary
היא רוצה לישון
לישון
�ן
אתם, הם
�ם
Bye
Hello, world!
test
(我将所有内容保存在UTF-8中)。
这是很奇怪的。有什么建议么?
(这不是“Console2”问题*-在“常规” Windows控制台上会显示相同的问题,只是在那里您看不到希伯来字形)。
*使用“Console”(也称为“Console2”)-这是一个不错的小实用程序,可在Windows控制台上使用Unicode-例如,请参见此处:
http://www.hanselman.com/blog/Console2ABetterWindowsCommandPrompt.aspx
**注意:在控制台上,您当然必须说:
chcp 65001
最佳答案
您是否尝试过perlmonk的解决方案?
它还使用:unix
来避免控制台缓冲区。
这是该链接的代码:
use Win32::API;
binmode(STDOUT, ":unix:utf8");
#Must set the console code page to UTF8
$SetConsoleOutputCP= new Win32::API( 'kernel32.dll', 'SetConsoleOutputCP', 'N','N' );
$SetConsoleOutputCP->Call(65001);
$line1="\x{2554}".("\x{2550}"x15)."\x{2557}\n";
$line2="\x{2551}".(" "x15)."\x{2551}\n";
$line3="\x{255A}".("\x{2550}"x15)."\x{255D}";
$unicode_string=$line1.$line2.$line3;
print "THIS IS THE CORRECT EXAMPLE OUTPUT IN PURE PERL: \n";
print $unicode_string;
关于Perl:将Unicode字符串打印到Windows控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370720/