#!/usr/bin/perl
######################################################################
# eg/tw/mb_practical.pl - ä¸ææ·å­åçåºå®æ¬ä½ä¿®åª
#
# æ­¤ä¾å±ç¤ºï¼ä¸åå°å°çå¯¦åä»»åï¼ï¼
#   å° Shift_JIS ä¸è¡ä¿®åªå°åºå®é¡¯ç¤ºå¯¬åº¦ï¼ä¾åºå®
#   æ¬ä½è¼¸åºï¼åå½¢å­åç® 1 æ¬ï¼å¨å½¢å­åç® 2 æ¬
#   ï¼ç¶å¸ç 1:2 æ¯ï¼ï¼ä¸çµä¸å¨éçåééä½åçµå­åã
#
# è CORE çåå¥ï¼
#   å¤©çç CORE substr(EXPR, 0, N) å¨ç¬¬ N åä½åçµåï¼å¯
#   è½çä¸æ¸ç©ºçåå° byte -- å­åç ´æçä¸åãéè£¡æ
#   åç¨ mb::split('') èµ°éæ´åå­åï¼ä»¥ byte é·åº¦é
#   æ¯å­åå¯¬åº¦ï¼1 byte -> 1 æ¬ï¼2 byte -> 2 æ¬ï¼ï¼ä¸¦å¨
#   è¶åºé ç®ååæ­¢ãmb::length() ç¢ºèªçµææ¯æ´æ¸åå­åã
#
# æ³¨ï¼åå§ç¢¼è \xHH è³æç¶­æ US-ASCIIï¼æ¬æªçº
# UTF-8ï¼åè¨»è§£å¨å°åçºç¹é«ä¸­æï¼ã
#
#     perl eg/tw/mb_practical.pl
#
######################################################################
use strict;
use vars qw($line $budget $out $col $ch $w $aiu $octet_cut $char_cut);

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

# A B C ç¶å¾ä¸åå¨å½¢å¹³åå a i u ç¶å¾å©ååå½¢çååã
#   ASCII A B C            : æ¯å 1 æ¬
#   å¨å½¢ a(\x82\xA0) i(\x82\xA2) u(\x82\xA4) : æ¯å 2 æ¬
#   åå½¢ ka(\xB6) ki(\xB7)                   : æ¯å 1 æ¬
$line   = "ABC\x82\xA0\x82\xA2\x82\xA4\xB6\xB7";
$budget = 7;   # ä¿®åªå° 7 é¡¯ç¤ºæ¬

# å­åéçå®å¨ãæç¥å¯¬åº¦çä¿®åªã
$out = '';
$col = 0;
for $ch (mb::split('', $line)) {
    $w = length($ch);        # 1 byte -> 1 æ¬ï¼2 byte -> 2 æ¬
    last if $col + $w > $budget;
    $out .= $ch;
    $col += $w;
}

# ABC (3 æ¬) + a (2) + i (2) = 7 æ¬ï¼u ææº¢åºèè¢«ä¸æ£ï¼ææ«
# å°¾éä½åçµå­åä¿æå®æ´ã
print "input chars      : ", mb::length($line), "\n";        # 8
print "budget columns   : $budget\n";                        # 7
print "kept chars       : ", mb::length($out), "\n";         # 5
print "used columns     : $col\n";                           # 7
print "kept bytes       : ", length($out), "\n";             # 7

# å°åéä½åçµè³æçå°æ¯ï¼ä»¥åºå®ä½åçµæ¸åå²
# å¯è½è½å¨å­åå§é¨ãå¹³åå a i u å¨æ¯éä½åçµï¼æ
# å¥æ¸ byte é·åº¦è¡¨ç¤ºåå²ææ·äºå­åï¼mb::substr ç¸½æ¯
# å¨å­åéçåæ­¢ï¼éè£¡æ¯å¶æ¸ byte é·åº¦ï¼ã
$aiu       = "\x82\xA0\x82\xA2\x82\xA4";
$octet_cut = substr($aiu, 0, 3);        # a + ä¸åæ¸ç©ºçåå° byte
$char_cut  = mb::substr($aiu, 0, 1);    # æ°å¥½æ¯ a
print "CORE substr 3oct : ", length($octet_cut), " bytes (odd -> split)\n"; # 3
print "mb::substr 1char : ", length($char_cut),  " bytes (whole char)\n";   # 2

exit 0;
