eg/tw/mb_length.pl

filter: Statementstmt 100% 28 / 28 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 100% 33 / 33 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« eg/tr/mb_length.pl ↑ Summary eg/ur/mb_length.pl »
1 #!/usr/bin/perl
2 ######################################################################
3 # eg/tw/mb_length.pl - 用 mb 比較字元數與位元組數
4 #
5 # 此例展示:
6 # CORE 的 length() 計算位元組(byte);mb::length() 依所選
7 # 腳本編碼,將整個多位元組字元算作 1。mb::substr() 與
8 # mb::index() 也以字元為單位,故雙位元組字元不會被攔斷。
9 #
10 # 與 CORE 的區別:
11 # length("\x82\xA0") 為 2(byte),但 mb::length("\x82\xA0") 為 1
12 # (一個 Shift_JIS 平假名)。
13 #
14 # 注:原始碼與 \xHH 資料維持 US-ASCII;本檔為
15 # UTF-8(僅註解在地化為繁體中文)。
16 #
17 # perl eg/tw/mb_length.pl
18 #
19 ######################################################################
20 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use vars qw($aiu $byte_len $char_len $head $tail $pos);
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 1 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use lib "$FindBin::Bin/../../lib";
Subroutine BEGIN: called CC=1 SCAR=0.0
25 1 ▶use mb;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 mb::set_script_encoding('sjis');
27  
28 # Shift_JIS 三個平假名,共 6 個 byte:
29 # \x82\xA0 a \x82\xA2 i \x82\xA4 u
30 1 $aiu = "\x82\xA0\x82\xA2\x82\xA4";
31  
32 # CORE length() 計 byte;mb::length() 計字元。
33 1 $byte_len = length($aiu);
34 1 $char_len = mb::length($aiu);
35 1 print "byte length : $byte_len\n"; # 6
36 1 print "character length : $char_len\n"; # 3
37  
38 # mb::substr() 以字元為單位切割,故雙位元組字元不會切
39 # 成一半。前兩個字元恰好是 4 個 byte 的字串。
40 1 $head = mb::substr($aiu, 0, 2);
41 1 $tail = mb::substr($aiu, 2);
42 1 print "first 2 chars : ", length($head), " bytes\n"; # 4
43 1 print "remaining chars : ", length($tail), " bytes\n"; # 2
44  
45 # mb::index() 回報的位置是字元而非 byte。第三個
46 # 字元在 byte 4 開始,但字元索引為 2。
47 1 $pos = mb::index($aiu, "\x82\xA4");
48 1 print "index of 3rd char: $pos\n"; # 2
49  
50 1 exit 0;
« eg/tr/mb_length.pl ↑ Summary eg/ur/mb_length.pl »