Perl:为什么Term :: Readline会破坏STDIN / STDOUT?

时间:2012-01-10 21:37:00

标签: perl utf-8 readline

如果我创建新的Term :: Readline对象(并传递binmoded STDIN和STDOUT),则输入和输出将被模拟。例如:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;
use utf8::all;
use Term::ReadLine;

my $X = <>;
chomp $X;
say "õ $X";

my $term = new Term::ReadLine ('test', \*STDIN, \*STDOUT);

say "õ $X";
$X = <>;
chomp $X;
say "õ $X";

__END__
got:
õ
õ õ
� �
õ
� õ

如果我输入拉丁文1中不存在的字符,我会收到“宽字符”警告并输出更好,但仍然不正确:

ž
õ ž
Wide character in print at db.test.pl line 20, <> line 1.
õ ž
ž
� ž

使用Term :: Readline时如何正确设置IO?

1 个答案:

答案 0 :(得分:3)

构造函数将“stdio”图层添加到需要删除的流中。请参阅PerlIO中的:pop

#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
use utf8::all;
use Devel::Peek;
use Term::ReadLine;

my $X = <>;
Dump $X;
chomp $X;
say "õ $X";

say join ' ', PerlIO::get_layers('STDIN');
say join ' ', PerlIO::get_layers('STDOUT');

my $term = new Term::ReadLine ('test', \*STDIN, \*STDOUT);

say join ' ', PerlIO::get_layers('STDIN');
say join ' ', PerlIO::get_layers('STDOUT');

binmode 'STDIN', ':pop';
binmode 'STDOUT', ':pop';

say join ' ', PerlIO::get_layers('STDIN');
say join ' ', PerlIO::get_layers('STDOUT');

say "õ $X";
$X = <>;
Dump $X;
chomp $X;
say "õ $X";

__END__
ž
õ ž
SV = PV(0x753160) at 0x778968
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK,UTF8)
  PV = 0x766830 "\305\276"\0 [UTF8 "\x{17e}"]
  CUR = 2
  LEN = 80
unix perlio encoding(utf-8-strict) utf8
unix perlio encoding(utf-8-strict) utf8
unix perlio encoding(utf-8-strict) utf8 stdio
unix perlio encoding(utf-8-strict) utf8 stdio
unix perlio encoding(utf-8-strict) utf8
unix perlio encoding(utf-8-strict) utf8
õ ž
ž
SV = PV(0x753160) at 0x778968
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK,UTF8)
  PV = 0x766830 "\305\276\n"\0 [UTF8 "\x{17e}\n"]
  CUR = 3
  LEN = 80
õ ž