本文介绍了如何在不影响文件IO的情况下使Perl尊重STDIN/STDOUT/STDERR的语言环境编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确保Perl在STDIN/STDOUT/STDERR中使用语言环境编码(如LANG = en_US.UTF-8)的最佳方法是什么,而又不影响文件IO?

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?

如果我使用

use open ':locale';
say "mañana";
open (my $f, '>', 'test.txt'); say $f "mañana";

然后将语言环境编码用于STDIN/STDOUT/STDERR,但在test.txt中也使用了该语言,它的行为不太好:您不希望文件的编码取决于您的登录方式.

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.

推荐答案

首先,您应该使用

use open ':std' => ':locale';

代替

use open ':locale';


第二,您应该为文本文件指定所需的编码.


Second, you should be specifying the encoding you want for the text file.

open(my $fh, '>:encoding(UTF-8)', $qfn)

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

use open ':std' => ':locale';
open(my $fh, '>:encoding(UTF-8)', $qfn)   # Text
open(my $fh, '>:raw',             $qfn)   # Binary

(如果愿意,可以将binmode($fh);代替:raw用于二进制文件.)

(You can use binmode($fh); instead of :raw for binary files, if you prefer.)

这篇关于如何在不影响文件IO的情况下使Perl尊重STDIN/STDOUT/STDERR的语言环境编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:06