我试图弄清楚如何使用 Term::ReadLine
从终端读取 Unicode 输入。事实证明,如果我在提示符下输入 Unicode 字符,返回的字符串会根据不同的设置而有所不同。 (我正在运行 Ubuntu 14.10,并已安装 Term::ReadLine::Gnu
)。例如(p.pl
):
use open qw( :std :utf8 );
use strict;
use warnings;
use Devel::Peek;
use Term::ReadLine;
my $term = Term::ReadLine->new('ProgramName');
$term->ornaments( 0 );
my $ans = $term->readline("Enter message: ");
Dump ( $ans );
运行 p.pl
并在提示符处输入 å
给出输出:
Enter message: å
SV = PV(0x83a5a0) at 0x87c080
REFCNT = 1
FLAGS = (PADMY,POK,pPOK)
PV = 0x917500 "\303\245"\0
CUR = 2
LEN = 10
因此返回的字符串$ans
尚未设置UTF-8
标志。但是,如果我使用 perl -CS p.pl
运行该程序,输出为:
Enter message: å
SV = PVMG(0x24c12e0) at 0x23050a0
REFCNT = 1
FLAGS = (PADMY,POK,pPOK,UTF8)
IV = 0
NV = 0
PV = 0x248faf0 "\303\245"\0 [UTF8 "\x{e5}"]
CUR = 2
LEN = 10
$ans
上的 UTF-8 标志已正确设置。所以第一个问题是:为什么命令行选项 -CS
与使用编译指示 use open qw( :std :utf8 )
不同?
接下来,我使用 -CS
选项测试了 Term::ReadLine::Stub
:
$ PERL_RL=Stub perl -CS p.pl
现在的输出是:
Enter message: å
SV = PV(0xf97260) at 0xfd90c8
REFCNT = 1
FLAGS = (PADMY,POK,pPOK,UTF8)
PV = 0x10746e0 "\303\203\302\245"\0 [UTF8 "\x{c3}\x{a5}"]
CUR = 4
LEN = 10
并且输出字符串$ans
已被双重编码,因此输出已损坏。这是一个错误,还是预期的行为?
最佳答案
正如 Denis Ibaev 在他的 answer 中所解释的那样,问题是 Term::ReadLine
不读取 STDIN
,它打开一个新的输入文件句柄。作为调用 binmode($term->IN, ':utf8')
的替代方法,事实证明可以使用命令行选项 -CS
或 使用 open qw( :std :utf8)
通过将 STDIN
作为参数提供给 Term::与
,如此问题的答案中所述:Term::Readline: encoding-question 。 Term::ReadLine
一起使用ReadLine->new()
例如:
use strict;
use utf8;
use open qw( :std :utf8 );
use warnings;
use Term::ReadLine;
my $term = Term::ReadLine->new('Test', \*STDIN, \*STDOUT);
my $answer = $term->readline( 'Enter input: ' );
关于perl - 将 Term::ReadLine 与 Unicode 输入结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573117/