Perl Unicode Cookbook: Decode Standard Filehandles as Locale Encoding
℞ 16: Declare STD{IN,OUT,ERR}
to be in locale encoding
Always convert to and from your desired encoding at the edges of your programs. This includes the standard filehandles STDIN
, STDOUT
, and STDERR
. While it may be most common for modern operating systems to support UTF-8 in filehandle settings, you may need to use other encodings.
Perl can respect your current locale settings for its default filehandles. Start by installing the Encode::Locale module from the CPAN.
# cpan -i Encode::Locale
use Encode;
use Encode::Locale;
# or as a stream for binmode or open
binmode STDIN, ":encoding(console_in)" if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
The Encode::Locale
module allows you to use “whatever encoding the attached terminal expects” for input and output filehandles attached to terminals. It also allows you to specify “whatever encoding the file system uses for file names”; see the documentation for more.
Previous: ℞ 15: Decode Standard Filehandles as UTF-8
Series Index: The Standard Preamble
Tags
Feedback
Something wrong with this article? Help us out by opening an issue or pull request on GitHub