eg/en/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/bn/mb_length.pl ↑ Summary eg/fr/mb_length.pl »
1 #!/usr/bin/perl
2 ######################################################################
3 # eg/en/mb_length.pl - counting characters vs bytes with mb
4 #
5 # What this shows:
6 # CORE length() counts OCTETS; mb::length() counts whole multibyte
7 # CHARACTERS under the selected script encoding. mb::substr() and
8 # mb::index() work in character units too, so a double-byte character
9 # is never cut in half.
10 #
11 # How it differs from CORE:
12 # length("\x82\xA0") is 2 (bytes), but mb::length("\x82\xA0") is 1
13 # (one Shift_JIS hiragana).
14 #
15 # The source is deliberately US-ASCII: the multibyte data is written
16 # with \xHH byte escapes so the example stays portable while mb still
17 # treats those bytes as whole characters. Run from the distribution
18 # root (or after install):
19 #
20 # perl eg/en/mb_length.pl
21 #
22 ######################################################################
23 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use vars qw($aiu $byte_len $char_len $head $tail $pos);
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 1 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use lib "$FindBin::Bin/../../lib";
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶use mb;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 1 mb::set_script_encoding('sjis');
30  
31 # Three hiragana letters in Shift_JIS, six bytes in total:
32 # \x82\xA0 a \x82\xA2 i \x82\xA4 u
33 1 $aiu = "\x82\xA0\x82\xA2\x82\xA4";
34  
35 # CORE length() counts bytes; mb::length() counts characters.
36 1 $byte_len = length($aiu);
37 1 $char_len = mb::length($aiu);
38 1 print "byte length : $byte_len\n"; # 6
39 1 print "character length : $char_len\n"; # 3
40  
41 # mb::substr() slices in character units, so a double-byte character is
42 # never cut in half. The first two characters are a clean 4-byte string.
43 1 $head = mb::substr($aiu, 0, 2);
44 1 $tail = mb::substr($aiu, 2);
45 1 print "first 2 chars : ", length($head), " bytes\n"; # 4
46 1 print "remaining chars : ", length($tail), " bytes\n"; # 2
47  
48 # mb::index() reports the position in characters, not bytes. The third
49 # character starts at byte 4, but at character index 2.
50 1 $pos = mb::index($aiu, "\x82\xA4");
51 1 print "index of 3rd char: $pos\n"; # 2
52  
53 1 exit 0;
« eg/bn/mb_length.pl ↑ Summary eg/fr/mb_length.pl »