问题
What is the best way to ensure Perl uses the locale encoding (as in LANG=en_US.UTF-8) for STDIN/STDOUT/STDERR, without affecting file IO?
If I use
use open ':locale';
say "mañana";
open (my $f, '>', 'test.txt'); say $f "mañana";
then the locale encoding is used for STDIN/STDOUT/STDERR, but also in test.txt, which is not very well-behaved: you don't want the encoding of a file to depend on the way you logged in.
回答1:
First, you should be using
use open ':std' => ':locale';
instead of
use open ':locale';
Second, you should be specifying the encoding you want for the text file.
open(my $fh, '>:encoding(UTF-8)', $qfn)
or
use open IO => ':encoding(UTF-8)';
open(my $fh, '>', $qfn)
All together:
use open ':std' => ':locale';
use open IO => ':encoding(UTF-8)';
open(my $fh, '>', $qfn) # Text
open(my $fh, '>:raw', $qfn) # Binary
or
use open ':std' => ':locale';
open(my $fh, '>:encoding(UTF-8)', $qfn) # Text
open(my $fh, '>:raw', $qfn) # Binary
(You can use binmode($fh);
instead of :raw
for binary files, if you prefer.)
来源:https://stackoverflow.com/questions/14399629/how-can-i-get-perl-to-respect-the-locale-encoding-for-stdin-stdout-stderr-witho