作者kipi91718 (Renewal Process)
看板Perl
标题[问题] 字串经过encode之後的length
时间Sat Nov 17 09:26:23 2018
各位大大好,初次在本版发文,请多指教。
在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://webptt.com/cn.aspx?n=bbs/Perl/M.1542417987.A.BD4.html
※ kipi91718:转录至看板 ask 11/17 13:54