0

パート3(パート2はここにあります)(パート1はここにあります

これが私が使用しているperlModです:Unicode :: String

私の呼び方:

print "Euro: ";
print unicode_encode("€")."\n";
print "Pound: ";
print unicode_encode("£")."\n";

この形式を返したい:

€ # Euro
£ # Pound

関数は以下のとおりです。

sub unicode_encode {

    shift() if ref( $_[0] );
    my $toencode = shift();
    return undef unless defined($toencode);

    print "Passed: ".$toencode."\n";

    Unicode::String->stringify_as("utf8");
    my $unicode_str = Unicode::String->new();
    my $text_str    = "";
    my $pack_str    = "";

    # encode Perl UTF-8 string into latin1 Unicode::String
    #  - currently only Basic Latin and Latin 1 Supplement
    #    are supported here due to issues with Unicode::String .
    $unicode_str->latin1($toencode);

    print "Latin 1: ".$unicode_str."\n";

    # Convert to hex format ("U+XXXX U+XXXX ")
    $text_str = $unicode_str->hex;

    # Now, the interesting part.
    # We must search for the (now hex-encoded)
    #       Unicode escape sequence.
    my $pattern =
'U\+005[C|c] U\+0058 U\+00([0-9A-Fa-f])([0-9A-Fa-f]) U\+00([0-9A-Fa-f])([0-9A-Fa-f]) U\+00([0-9A-Fa-f])([0-9A-Fa-f]) U\+00([0-9A-Fa-f])([0-9A-Fa-f])';

    # Replace escapes with entities (beginning of string)
    $_ = $text_str;
    if (/^$pattern/) {
        $pack_str = pack "H8", "$1$2$3$4$5$6$7$8";
        $text_str =~ s/^$pattern/\&#x$pack_str/;
    }

    # Replace escapes with entities (middle of string)
    $_ = $text_str;
    while (/ $pattern/) {
        $pack_str = pack "H8", "$1$2$3$4$5$6$7$8";
        $text_str =~ s/ $pattern/\;\&#x$pack_str/;
        $_ = $text_str;
    }

    # Replace "U+"  with "&#x"      (beginning of string)
    $text_str =~ s/^U\+/&#x/;

    # Replace " U+" with ";&#x"     (middle of string)
    $text_str =~ s/ U\+/;&#x/g;

    # Append ";" to end of string to close last entity.
    # This last ";" at the end of the string isn't necessary in most parsers.
    # However, it is included anyways to ensure full compatibility.
    if ( $text_str ne "" ) {
        $text_str .= ';';
    }

    return $text_str;
}

同じ出力を取得する必要がありますが、Latin-9文字もサポートする必要がありますが、Unicode::Stringはlatin1に制限されています。これを回避する方法について何か考えはありますか?

他にもいくつか質問があり、Unicodeとエンコーディングについてある程度理解していると思いますが、時間の問題もあります。

私を助けてくれた人に感謝します!

4

1 に答える 1

2

既に述べたように、Unicode::String は適切なモジュールの選択ではありません。Perl には「Encode」というモジュールが付属しており、必要なことはすべて実行できます。

次のような Perl の文字列があるとします。

my $euro = "\x{20ac}";

次のように、Latin-9 のバイト文字列に変換できます。

my $bytes = encode("iso8859-15", $euro);

$bytes変数には \xA4 が含まれます。

または、次のように Perl に出力をファイルハンドルに自動的に変換させることもできます。

binmode(STDOUT, ":encoding(iso8859-15)");

Encodeモジュールのドキュメントを参照できます。また、PerlIOはエンコーディング層についても説明しています。

あなたがこの最後のアドバイスを無視しようと決心していることは承知していますが、最後にもう一度だけお伝えします。Latin-9 は従来のエンコーディングです。Perl は、Latin-9 データを非常に喜んで読み取り、その場で (binmode を使用して) UTF-8 に変換できます。移行する必要がある Latin-9 データを生成するソフトウェアをこれ以上作成するべきではありません。

于 2010-06-18T19:29:28.097 に答える