use open ':std'を使うのが一番短く済む気がする.この場合STDERRも:utf8を通しているのでencodeせずに出力することができる.
#!/usr/bin/perl use strict; use warnings; use utf8; use open ':utf8'; use open ':std'; while (<>) { print if (/[ぁ-ん]/); print STDERR "$_\n"; }
use open ':std'はperldoc openで説明されている.
The ":std" subpragma on its own has no effect, but if combined with the":utf8" or ":encoding" subpragmas, it converts the standard filehandles(STDIN, STDOUT, STDERR) to comply with encoding selected for input/out‐put handles. For example, if both input and out are chosen to be ":utf8", a ":std" will mean that STDIN, STDOUT, and STDERR are also in ":utf8". On the other hand, if only output is chosen to be in ":encoding(koi8r)", a ":std" will cause only the STDOUT and STDERR to be in "koi8r". The ":locale" subpragma implicitly turns on ":std".