標 題 UTF8下中文處理

2021-05-18 08:55:40 字數 3427 閱讀 6229

標 題:utf8中文處理

發信站: 水木社群 (mon sep 11 21:22:53 2006), 站內

我來總結一下吧。先建乙個檔案,寫上中文兩個字。執行下面乙個程式:

use strict;

use warnings;

use encode;

my $str_code = "中文";

my $file = "test.txt";

open(my $fh, $file) || die "can't open file $file: $!";

chomp(my $str_file = <$fh>);

close $fh;

open(my $fh_utf8, "<:utf8", $file) || die "can't open file $file: $!";

chomp(my $str_fileu = <$fh_utf8>);

close $fh_utf8;

test_utf8($str_code, "code");

test_utf8($str_file, "file");

test_utf8($str_fileu, "file(utf8layer)");

# print $str_code, "/n";

# print $str_file, "/n";

# print $str_fileu, "/n";

encode::_utf8_on($str_code);

encode::_utf8_on($str_file);

test_utf8($str_code, "code");

test_utf8($str_file, "file");

sub test_utf8 else

my @chars = split('', $str);

# print join("/t", @chars), "length: ", scalar(@chars);

if (scalar(@chars)==2) else

print "/n";

}結果如下:

string from code,utf8flag is off. can't match chinese character.

string from file,utf8flag is off. can't match chinese character.

string from file(utf8layer),utf8flag is on. can match chinese character.

turn on utf flag:

string from code,utf8flag is on. can match chinese character.

string from file,utf8flag is on. can match chinese character.

所以如果要想使用漢字作為乙個字元的特性,就要在 open 裡指明 io layer 為

utf8,同樣,輸出指明utf8,然後在指令碼裡寫 useutf8

這樣你就不用擔心utf8下的亂碼,又能享受漢字做為乙個字元來寫正則表達

的暢快。

如果不知道我上面說的意思,我就給乙個例子:

use strict;

use warnings;

use encode;

useutf8;

my $file = "test.txt";

my $outfile = "test-out.txt";

# open(my $fh, $file) || die "can't open file $file: $!";

# open(my $out, '>:utf8', $outfile) || die "can't open file $outfile: $!";

# select $out;

open(my $fh, '<:utf8', $file) || die "can't open file $file: $!";

binmode stdout, ":utf8";

while (<$fh>)

print $_;}}

test.txt 中的內容是:"求/n漢/n汁/n汗/n汕/n江/n"(每個漢字一行的意思)。

這個例子中,有好幾個組合:

1. 不使用utf8指令,open 中也不使用utf8

這時所有行都匹配。因為正則表達中是三個位元組(我假定你也用utf8來編碼

**,如果不是,可以不匹配任何行),而所有輸入的行中都含有這三個位元組中

的乙個,事實上 test.txt 是我精心挑選的,前兩個位元組都相同的漢字。

2. 不使用utf8指令, open 中使用utf8.

不能匹配任何行。因為輸入檔案中是漢字,而正則表達是三個位元組。

3. 使用utf8指令,open 中不使用utf8

也不能匹配任何行。因為正則表達中是乙個漢字,而輸入檔案是乙個個的位元組。

4. 使用utf8指令,open 中也使用utf8

正確匹配一行。

至於輸出的 warning,這確實這是乙個小小的 warning,不會影響結果。如果不

想有這個 warning,最好的辦法是用 binmode 或者在 open 中指定使用utf8

layer。或者對於 warning 的字串用 encode 模組中 _utf8_on 函式,強制

加上utf8flag.

utf 8的中文漢字

從字元編碼講起。1 美國人首先對其英文本元進行了編碼,也就是最早的ascii碼,用乙個位元組的低7位來表示英文的128個字元,高1位統一為0 2 後來歐洲人發現尼瑪你這128位哪夠用,比如我高貴的法國人字母上面的還有注音符,這個怎麼區分,得,把高1位編進來吧,這樣歐洲普遍使用乙個全位元組進行編碼,最...

utf 8下接受中文引數問題

xx.aspx?id 中文 utf 8 下 到底如何接收這個中文 1 你可以考慮把中文都轉化成這種 形式 2 string msg server.urlencode 漢字 response.redirect webform.aspx?msg msg 接收 string msg server.urld...

網頁utf 8亂碼 utf8亂碼

複製 在前 在windows作業系統上使用ie作為瀏覽器時。常常會發生這樣的問題 在瀏覽使用utf 8編碼的網頁時,瀏覽器無法自動偵測 即沒有設定 自動選擇 編碼格式時 該頁面所用的編碼。即使網頁已經宣告過編碼格式 由此造成某些含有中文utf 8編碼的頁面產生空白輸出。由於utf 8為3個位元組表示...