user620201
user620201

Reputation: 1

Perl read file with perl unicode representation

I try to read a a.txt file, which is in perl's unicode representation. \x{7ec8}

I used the following perl code test.txt to read.

binmode STDOUT, ":utf8";  
while ( <> ) {  
  chomp;  
  print "$s_\n";  
}  
my $input = "\x{7ec8}";  
print "$input\n";  

I run the cat a.txt |perl test.pl, and the output is

\x{7ec8}  
终

This means that the perl code can't recognize the unicode representation from a.txt, but can recognize inside the code.

Upvotes: 0

Views: 728

Answers (1)

mscha
mscha

Reputation: 6830

You also need to put STDIN in utf8-mode:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

binmode STDIN, ":utf8";  
binmode STDOUT, ":utf8";  
while ( <> ) {  
  chomp;  
  say;
}  
my $input = "\x{7ec8}";  
print "$input\n";  

outputs:

终
终

Another option is to simply

use open qw(:utf8 :std);

which opens all file handles, and STDIN/STDOUT/STDERR, in utf8-mode. See perldoc open.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use open qw(:utf8 :std);

while ( <> ) {  
  chomp;  
  say;
}  
my $input = "\x{7ec8}";  
print "$input\n";  

Upvotes: 3

Related Questions