Practice of Programming

プログラム とか Linuxとかの話題

@ARGVにUTF8フラグをたてる

@ARGVには、普通UTF8フラグはつきません。どうやってフラグをつけるのか調べてみました。

その後、ブックマークコメントを見て、モジュール探したら見つけましたんで、追加しました。

-C か環境変数でやる

こちらで見つけました.
起動オプション-Cか環境変数PERL_UNICODEにAを与えてやります。

perl -CA -e 'print utf8::is_utf8($ARGV[0]);' あああ
PERL_UNICODE=A perl -e 'print utf8::is_utf8($ARGV[0]);' あああ

-CやPERL_UNICODEが取れる値は、perldoc perlrun にあります。以下、抜粋。

       -C [number/list]
            The "-C" flag controls some Unicode of the Perl Unicode features.

            As of 5.8.1, the "-C" can be followed either by a number or a list of option letters.
            The letters, their numeric values, and effects are as follows;
            listing the letters is equal to summing the numbers.

                I     1    STDIN is assumed to be in UTF-8
                O     2    STDOUT will be in UTF-8
                E     4    STDERR will be in UTF-8
                S     7    I + O + E
                i     8    UTF-8 is the default PerlIO layer for input streams
                o    16    UTF-8 is the default PerlIO layer for output streams
                D    24    i + o
                A    32    the @ARGV elements are expected to be strings encoded in UTF-8
                L    64    normally the "IOEioA" are unconditional,
                           the L makes them conditional on the locale environment
                           variables (the LC_ALL, LC_TYPE, and LANG, in the order
                           of decreasing precedence) -- if the variables indicate
                           UTF-8, then the selected "IOEioA" are in effect

IOE(= S)あたりは、use open ":utf8"; use open ":std"; するより、楽かもーですねぇ。

Encode::Argv を使う

牧さん作のEncode::Argvというのがあって、これを使えばいいようです。

% perl -e 'use Encode::Argv 'utf8'; print utf8::is_utf8($ARGV[0])' あああ

引数は、@ARGVに渡される文字列の文字コードです。


引数を与えない場合は、宮川さん作のTerm::Encodingが、ターミナルの文字コードを判断します。
が、依存モジュールにはなっていないので、別途インストールしましょう。

% perl -e 'use Encode::Argv; print utf8::is_utf8($ARGV[0])' あああ


ちなみに、2つ引数を与えると、decodeするんじゃなくて、別の文字コードに変換するようです。

% perl -e 'use Encode::Argv utf8 => "euc-jp"; print utf8::is_utf8($ARGV[0])' あああ

ので、フラグは立ちません。