How can I get Perl to respect the locale encoding for STDIN/STDOUT/STDERR, without affecting file IO?

孤者浪人 提交于 2019-12-10 17:47:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!