看板 Perl 關於我們 聯絡資訊
各位大大好,初次在本版發文,請多指教。 在perldoc上面有敘述到: When you run $octets = encode("utf8", $string) , then $octets might not be equal to $string. Though both contain the same data, the UTF8 flag for $octets is always off. When you encode anything, the UTF8 flag on the result is always off, even when it contains a completely valid utf8 string. https://perldoc.perl.org/Encode.html 我測試了以下三個狀況,在perl 5.26.1的環境下確認原始字串都是utf-8, 但在encode之後用length去檢測發現結果不太能完全理解。 1. $str1 = "中文"; length( $str1 ); #答案為6,因為UTF8 flag off,這是在算byte數,中文佔3 Bytes Encode::_utf8_on( $str1 ); length( $str1 ); #答案為2,因為UTF8 flag on,這是在算中文字數量 Encode::_utf8_off( $str1 ); length( $str1 ); #答案為為6,一樣是UTF8 flag off的狀況,為byte數 $str1_e = encode("UTF-8", str1); length($str1_e); #答案為12,不知道是在計算什麼的數量才會得到12 2. $str2 = "English"; length( $str2 ); #因為英文本來就只佔了1 Byte,所以答案為7 Encode::_utf8_on( $str2 ); length( $str2 ); #算字數一樣答案為7 Encode::_utf8_off( $str2 ); length( $str2 ); #7 Bytes $str2_e = encode("UTF-8", str2); length( $str2); #沒改變,一樣是7,是什麼原因呢? 3. $str3 = "ABC呢"; length( $str3 ); #英文 1*3 = 3 Bytes + 中文 3*1 = 3 Bytes 答案為6 Bytes Encode::_utf8_on( $str3 ); length( $str3 ); #共3英文字+1中文字 = 4個字 Encode::_utf8_off( $str3 ); length( $str3 ); #6,因為6 Bytes $str3_e = encode("UTF-8", str3); length( $str3_e); #答案為9,所以看起來中文在這情況下的結果是每字+6? 經過以上實測,比較有疑問的是encode到底做了什麼? 以至於讓length去偵測時,中文 會回傳6呢? 又問得更根本,在encode回來之後$octets送進length時, 究竟是被當作什麼型態在處理呢? 請版上專業的大大解惑,我可以200P作為微薄的謝禮,謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.226.177.46 ※ 文章網址: https://www.ptt.cc/bbs/Perl/M.1542417987.A.BD4.html kipi91718:轉錄至看板 ask 11/17 13:54