Perl:将Unicode字符串打印到Windows控制台

标签 perl unicode utf-8 console unicode-string

在将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/

相关文章:

perl - 如何从未命名的 Perl 模块导入所有 "our"变量而不列出它们?

perl - 安装 mod_perl 时出错

c++ - 如何将 sqlite3_mprintf() 与 UTF-16 字符串一起使用?

php - MySQL - 搜索瑞典语字符

c++ - 如何使用 C++11 语言环境设施将 UTF-8 用作字符串的内部表示?

php - 为什么 PHP 中的字符串连接使用句号 "."而不是加号 "+"?

perl - 在 Perl 中,如何通过菱形运算符对命令行上指定的所有文件进行两次传递?

python - 如何在 Python - Selenium 中将韩语作为 find_element_by_link_text() 的参数?

python - 从 python 向带有 windows-1251 编码的页面发送请求

javascript - 该对象中的数字与 UTF-8 兼容吗?