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