Perl版將UTF-8 -> big5 UAO

這是我第一個將PHP轉Perl的程式,也算是學一點Perl,Perl真是一個博大驚深的語言啊,老實說起來。某些方面比php簡單很多也直覺很多...XDrz

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/perl -w
#
# This perl script is using GNU General Public License v2.0
# renn999<AT>ccns.ncku.edu.tw
# http://renn999.twbbs.org
#
# USAGE:ucs2big5( $str );
#
# Big5 table(big5.txt)
# using from Ztrem
# http://zhouer.org/ZTerm/


print &ucs2big5('測試 試験 しけん');

sub ucs2big5 {
    my $ucs_str=shift;
    open FILE, "big5.txt";
    #binmode FILE; 
    my $len = length $ucs_str;
    my ($b1,$b2,$b3,$big5_code,$ucs_code,$big5_str);

    for( my $i = 0 ; $i < $len ; $i++ ) {
        $b1 = ord(substr $ucs_str, $i, 1);
        if( $b1 < 0x80 ) {
            $big5_str .= chr($b1);
        }
        elsif( $b1 >= 224 ) {
            #3code UTF-8
            $b1 -= 224;
            $b2 = ord(substr $ucs_str, ++$i, 1) - 128;
            $b3 = ord(substr $ucs_str, ++$i, 1) - 256;
            $ucs_code = $b1 * 4096 + $b2 * 64 + $b3;
            seek( FILE, $ucs_code * 2 , 0);
            read FILE, $big5_code, 2;
            $big5_str .= $big5_code;
        }
        elsif( $b1 >= 192 ) {
            #2code UTF-8
            $b1 -= 192;
            $b2 = ord(substr $ucs_str, ++$i, 1) - 256;
            $ucs_code = $b1 * 64 + $b2 ;
            seek( FILE, $ucs_code * 2 , 0 );
            read FILE, $big5_code, 2;
            $big5_str .= $big5_code;
        }else{
            $big5_str .= '?';
        }
    }

    if(length $big5_str != 0) {
        $big5_str;
    }
}

用pietty等UAO支援的程式應該可以看得出結果

Mon Oct. 12 2009
Comments

Comments