9

我在将 Unicode 字符串打印到 Windows 控制台时遇到了一个奇怪的问题*。

考虑这段文字:

אני רוצה לישון

Intermediary

היא רוצה לישון
אתם, הם
Bye
Hello, world!
test

假设它在一个名为“file.txt”的文件中。

当我去*:“type 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
4

4 回答 4

5

您是否尝试过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;
于 2012-02-21T01:38:59.233 回答
3

伙计们:继续研究 Perlmonks 的帖子,结果发现这更整洁更好:替换:
use Win32::API;
和:

$SetConsoleOutputCP= new Win32::API( 'kernel32.dll', 'SetConsoleOutputCP', 'N','N' );
$SetConsoleOutputCP->Call(65001);

和:

use Win32::Console;

和:

 Win32::Console::OutputCP(65001);

保持其他一切完好无损。
这更符合 Perl 简洁和神奇的精神。

于 2012-02-21T20:33:10.653 回答
1

您还可以利用Win32::Unicode::ConsoleWin32::Unicode::Native在 Windows 控制台上实现 unicode 打印。

于 2012-02-21T05:16:52.830 回答
0

此外,使用ConEmu时不会出现此行为,这也可以在 Windows 的命令控制台中启用正确的 Unicode 支持。

于 2018-11-13T21:57:58.380 回答