#!/usr/bin/perl
######################################################################
# eg/tw/mb_length.pl - ç¨ mb æ¯è¼å­åæ¸èä½åçµæ¸
#
# æ­¤ä¾å±ç¤ºï¼
#   CORE ç length() è¨ç®ä½åçµï¼byteï¼ï¼mb::length() ä¾æé¸
#   è³æ¬ç·¨ç¢¼ï¼å°æ´åå¤ä½åçµå­åç®ä½ 1ãmb::substr() è
#   mb::index() ä¹ä»¥å­åçºå®ä½ï¼æéä½åçµå­åä¸æè¢«ææ·ã
#
# è CORE çåå¥ï¼
#   length("\x82\xA0") çº 2ï¼byteï¼ï¼ä½ mb::length("\x82\xA0") çº 1
#   ï¼ä¸å Shift_JIS å¹³ååï¼ã
#
# æ³¨ï¼åå§ç¢¼è \xHH è³æç¶­æ US-ASCIIï¼æ¬æªçº
# UTF-8ï¼åè¨»è§£å¨å°åçºç¹é«ä¸­æï¼ã
#
#     perl eg/tw/mb_length.pl
#
######################################################################
use strict;
use vars qw($aiu $byte_len $char_len $head $tail $pos);

use FindBin;
use lib "$FindBin::Bin/../../lib";
use mb;
mb::set_script_encoding('sjis');

# Shift_JIS ä¸åå¹³ååï¼å± 6 å byteï¼
#     \x82\xA0  a   \x82\xA2  i   \x82\xA4  u
$aiu = "\x82\xA0\x82\xA2\x82\xA4";

# CORE length() è¨ byteï¼mb::length() è¨å­åã
$byte_len = length($aiu);
$char_len = mb::length($aiu);
print "byte length      : $byte_len\n";   # 6
print "character length : $char_len\n";   # 3

# mb::substr() ä»¥å­åçºå®ä½åå²ï¼æéä½åçµå­åä¸æå
# æä¸åãåå©åå­åæ°å¥½æ¯ 4 å byte çå­ä¸²ã
$head = mb::substr($aiu, 0, 2);
$tail = mb::substr($aiu, 2);
print "first 2 chars    : ", length($head), " bytes\n";   # 4
print "remaining chars  : ", length($tail), " bytes\n";   # 2

# mb::index() åå ±çä½ç½®æ¯å­åèé byteãç¬¬ä¸å
# å­åå¨ byte 4 éå§ï¼ä½å­åç´¢å¼çº 2ã
$pos = mb::index($aiu, "\x82\xA4");
print "index of 3rd char: $pos\n";        # 2

exit 0;
