简体   繁体   中英

Perl: why Term::Readline spoils STDIN/STDOUT?

If I create new Term::Readline object (and pass binmoded STDIN and STDOUT), input and output get mocked. Example:

#!/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:
õ
õ õ
� �
õ
� õ

If i input characters, which are not present in Latin 1, i get "Wide character" warning and output is better, but still not correct:

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

How properly set IO when using Term::Readline?

The constructor adds the 'stdio' layer to the streams which you need to remove. See :pop in PerlIO .

#!/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
õ ž

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM