[utf8] perl -C?

2010/04/29
By

以前程式碼遇上 utf-8 資料時總是比較麻煩,不是資料是 utf-8 或 big5 ,就是程式碼內含 big5 或 utf-8 字元。這些有了

use utf8;

後,都算比較好處理一點。

從 perl 5.8.1 之後, cmd 模式可以使用 -C 這個選項,來預先指定 IO 的 encoding。沒有 -C 的情況下,要指明輸出是 utf-8 格式時,程式碼要加上:

binmode(STDOUT, ‘:encoding(utf8)’);
# 或是
binmode(STDOUT, ‘:utf8′);

要指明輸入是 utf-8 時,就變成

binmode(STDIN, ‘:encoding(utf8)’);
# 或是
binmode(STDIN, ‘:utf8′);

要知道更多有關 binmode ,就看看說明文件就可以了。

而讀檔寫檔,也可以在 open 時指定 encoding,所以也是很方便。

open $FH, ‘<:utf8′, $file;

不過如果今天是要使用別人寫好的程式,要直接去改別人的程式碼,在某些時候(沒有權限?)就很麻煩。或是這次改了,下次更新就又忘了,相當不好玩啊。

所以 -C 就有用了,在文件裡是有如下的選擇:

  • 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
  • a 256 Set ${^UTF8CACHE} to -1, to run the UTF-8 caching code in
  • debugging mode.

所以,使用 perl -CIO xxxx.pl 等同於在程式內寫

binmode(STDIN, ‘:utf8′);
binmode(STDOUT, ‘:utf8′);

而預設對所以讀寫檔都用 utf-8 格式,可以使用 -CD (eq. -Cio) 。 如此一來,方便不少。 :)

當然,還有 PERL_UNICODE 這個 ENV 變數可以設定。

最後附個範例程式,可以自行測試:

Tags:

發表迴響

您的電子郵件位址並不會被公開。 必要欄位標記為 *

*


*