5.10.1

名前

perluniintro - Perl Unicode introduction

perluniintro - Perl Unicode の手引き

説明

This document gives a general idea of Unicode and how to use Unicode in Perl.

このドキュメントは、Unicode の一般的な考えと、 Perl で Unicode をどのように使うかを書いています。

Unicode

Unicode is a character set standard which plans to codify all of the writing systems of the world, plus many other symbols.

Unicode は、文字セットの標準です。 世界の全ての書記体系と、それに加えて、 他の多くのシンボルを体系化することを計画しています。

Unicode and ISO/IEC 10646 are coordinated standards that provide code points for characters in almost all modern character set standards, covering more than 30 writing systems and hundreds of languages, including all commercially-important modern languages. All characters in the largest Chinese, Japanese, and Korean dictionaries are also encoded. The standards will eventually cover almost all characters in more than 250 writing systems and thousands of languages. Unicode 1.0 was released in October 1991, and 4.0 in April 2003.

Unicode と、ISO/IEC 10646 は、よく調整された、コードポイントを提供する 標準です。 Unicode は、ほとんど全ての現代の文字セット標準、30 以上の書記体系と、 100 以上の言語を網羅します。 全ての商業的に重要な現代の言語を含みます。 もっとも大きい中国語、日本語、韓国語、それぞれの辞書の全ての文字もまた、 符号化されています。 この標準は、最終的には、250 の書記体系と、1000 以上の言語のほとんどすべての 文字を網羅する予定です。 Unicode 1.0 は、1991 年 10 月にリリースされ、Unicode 4.0 は、 2003 年 4 月にリリースされました。

A Unicode character is an abstract entity. It is not bound to any particular integer width, especially not to the C language char. Unicode is language-neutral and display-neutral: it does not encode the language of the text and it does not generally define fonts or other graphical layout details. Unicode operates on characters and on text built from those characters.

Unicode の 文字 は、抽象的な存在です。 Unicode の文字は、どんな特定の整数幅にも、特に、C 言語の char にも 束縛されません。 Unicode は、言語中立で、表示中立です: Unicode は、テキストの言語をエンコードしませんし、 一般的にはフォントや他のグラフィカルなレイアウトの詳細を定義しません。 Unicode は、文字と、それらの文字からなるテキストを操作します。

Unicode defines characters like LATIN CAPITAL LETTER A or GREEK SMALL LETTER ALPHA and unique numbers for the characters, in this case 0x0041 and 0x03B1, respectively. These unique numbers are called code points.

Unicode は、LATIN CAPITAL LETTER AGREEK SMALL LETTER ALPHA のような 文字と、その文字について固有の番号を定義します。 この場合は、それぞれ、0x0041 と、0x03B1 になります。 このような固有の番号は、コードポイント と呼ばれます。

The Unicode standard prefers using hexadecimal notation for the code points. If numbers like 0x0041 are unfamiliar to you, take a peek at a later section, "Hexadecimal Notation". The Unicode standard uses the notation U+0041 LATIN CAPITAL LETTER A, to give the hexadecimal code point and the normative name of the character.

Unicode 標準は、コードポイントに 16 進記法を使うのを好みます。 0x0041 のような番号に馴染みがなければ、後のセクション、 "Hexadecimal Notation" を覗いて見て下さい。 Unicode 標準は、U+0041 LATIN CAPITAL LETTER A という表記を使って、 16 進法のコードポイントと標準的な文字の名前を書きます。

Unicode also defines various properties for the characters, like "uppercase" or "lowercase", "decimal digit", or "punctuation"; these properties are independent of the names of the characters. Furthermore, various operations on the characters like uppercasing, lowercasing, and collating (sorting) are defined.

Unicode はまた、様々な文字の 性質 を定義します。 "大文字"、"小文字"、"10進数字"、"句読点" など; これらの性質は、文字の名前と独立です。 更に、様々な文字に対する操作、大文字化や小文字化や並び替えが 定義されています。

A Unicode character consists either of a single code point, or a base character (like LATIN CAPITAL LETTER A), followed by one or more modifiers (like COMBINING ACUTE ACCENT). This sequence of base character and modifiers is called a combining character sequence.

Unicode 文字は、1 つのコードポイントか、または、 (LATIN CAPITAL LETTER A のような)、基本文字 に続いて、 1つ以上の(COMBINING ACUTE ACCENT のような) 修飾語句 の、 どちらか一方から成っています。 この基本文字と修飾語句の順番は、combining character sequence と 呼ばれます。

Whether to call these combining character sequences "characters" depends on your point of view. If you are a programmer, you probably would tend towards seeing each element in the sequences as one unit, or "character". The whole sequence could be seen as one "character", however, from the user's point of view, since that's probably what it looks like in the context of the user's language.

これらの combining character sequence を "複数の文字" と呼ぶかどうかは、 考え方によります。 プログラマならば、おそらく、この順番のそれぞれの要素を、 1 つの単位か "文字" として、見ようとするでしょう。 全ての順番を一つの"文字"として見ることができます。 ですが、ユーザの考え方からは、おそらくユーザの言語の文脈でみえるような ものでしょう。

With this "whole sequence" view of characters, the total number of characters is open-ended. But in the programmer's "one unit is one character" point of view, the concept of "characters" is more deterministic. In this document, we take that second point of view: one "character" is one Unicode code point, be it a base character or a combining character.

この、文字の"すべての順番"の見え方では、文字の総数には、制限がありません。 ですが、プログラマーの"一つの単位は一つの文字"という考え方では、"文字" の 概念は、より決定論的です。 このドキュメントでは、2 番目の考え方を取ります: 1 つの"文字"は、1 つの Unicode のコードポイントであり、それは、基本文字か、 combining character であるとします。

For some combinations, there are precomposed characters. LATIN CAPITAL LETTER A WITH ACUTE, for example, is defined as a single code point. These precomposed characters are, however, only available for some combinations, and are mainly meant to support round-trip conversions between Unicode and legacy standards (like the ISO 8859). In the general case, the composing method is more extensible. To support conversion between different compositions of the characters, various normalization forms to standardize representations are also defined.

いくつかの組合せにとって、まだ構成されていない 文字があります。 たとえば、LATIN CAPITAL LETTER A WITH ACUTE は、 単一のコードポイントとして定義されています。 しかし、これらの、まだ構成されていない文字は、いくつかの組合せで 可能でしかありません。 そして、それらは、主に、Unicode と、レガシー標準(ISO 8859 のような)との 間の相互変換をサポートすることを意味します。 一般的なケースでは、構成する方法はより広がります。 違った構成間の変換をサポートするために、表現を標準化する、様々な normalization forms もまた定義されています。

Because of backward compatibility with legacy encodings, the "a unique number for every character" idea breaks down a bit: instead, there is "at least one number for every character". The same character could be represented differently in several legacy encodings. The converse is also not true: some code points do not have an assigned character. Firstly, there are unallocated code points within otherwise used blocks. Secondly, there are special Unicode control characters that do not represent true characters.

レガシーエンコーディングとの後方互換性のために、 "全ての文字に固有の番号" という考えは、少々壊れています: その代わりに、"少なくとも全ての文字に 1 つの番号" があります。 同じ文字が、いくつかのレガシーエンコーディングの中で、違うように 表現されていました。 逆は真でもなく: コードポイントには、文字が割り当てられていないものも あります。 1 番目に、使われているブロック内にもかかわらず、割り当てられていない コードポイントがあります。 2 番目に、特別な Unicode のコントロール文字があり、それらは、本物の文字を 表現しません。

A common myth about Unicode is that it would be "16-bit", that is, Unicode is only represented as 0x10000 (or 65536) characters from 0x0000 to 0xFFFF. This is untrue. Since Unicode 2.0 (July 1996), Unicode has been defined all the way up to 21 bits (0x10FFFF), and since Unicode 3.1 (March 2001), characters have been defined beyond 0xFFFF. The first 0x10000 characters are called the Plane 0, or the Basic Multilingual Plane (BMP). With Unicode 3.1, 17 (yes, seventeen) planes in all were defined--but they are nowhere near full of defined characters, yet.

Unicode について、よく知られている神話は、Unicode が、"16-ビット" である、 というものです。 Unicode は、0x0000 から、0xFFFF までで、0x10000 (か、65536)の 文字を表現するだけ、というものです。 これは真実ではありません。 Unicode 2.0(1996 年 7 月)から、Unicode は、21ビット(0x10FFFF)まで、 様々に定義されています。 Unicode 3.1(2001 年 3 月)から、文字は、0xFFFF を超えて、定義されました。 最初の 0x10000 文字は、 Plane 0、または、Basime Multilingual Plane(BMP)と、と呼ばれました。 Unicode 3.1 で、全部で 17(そう、17)の Plane が定義されました -- ですが、 まだ、定義された全文字のどこにも、まだ近くにありません。

Another myth is that the 256-character blocks have something to do with languages--that each block would define the characters used by a language or a set of languages. This is also untrue. The division into blocks exists, but it is almost completely accidental--an artifact of how the characters have been and still are allocated. Instead, there is a concept called scripts, which is more useful: there is Latin script, Greek script, and so on. Scripts usually span varied parts of several blocks. For further information see Unicode::UCD.

もう 1 つの神話は 256 文字ブロックが、何か言語を取り扱うことがある-- それぞれのブロックは言語か言語のセットで使われている文字を 定義するということです。 これもまた真実ではありません。 ブロックに分割されたものはありますが、それは、ほとんど完全に、 予想外のものです。 代わりに、scripts と呼ばれる、より有益なコンセプトがあります: Latin script と、Greek script と、その他のものがあります。 scripts は、ふつう、いくつかのブロックの変えられた部分を測っています。 詳しくは、Unicode::UCD を見て下さい。

The Unicode code points are just abstract numbers. To input and output these abstract numbers, the numbers must be encoded or serialised somehow. Unicode defines several character encoding forms, of which UTF-8 is perhaps the most popular. UTF-8 is a variable length encoding that encodes Unicode characters as 1 to 6 bytes (only 4 with the currently defined characters). Other encodings include UTF-16 and UTF-32 and their big- and little-endian variants (UTF-8 is byte-order independent) The ISO/IEC 10646 defines the UCS-2 and UCS-4 encoding forms.

Unicode のコードポイントは、抽象的な数字です。 この抽象的な数字を入出力するために、数字は、エンコードされる 必要が あるか、シリアライズされる か、どうか、しなければなりません。 Unicode は、複数の character encoding forms を定義していますが、 その中で、UTF-8 は、たぶん、もっとも有名です。 UTF-8 は、可変長のエンコーディングで、Unicode 文字を 1 から 6 バイト (現在定義されている文字では 4 バイトまでです)。 他のエンコーディングは、UTF-16 と UTF-32 と、それらの大小のエンディアンの 変形(UTF-8 は、バイトオーダーと独立です)を含みます。 ISO/IEC 10646 は、UCS-2 と UCS-4 の encoding forms を定義しています。

For more information about encodings--for instance, to learn what surrogates and byte order marks (BOMs) are--see perlunicode.

エンコーディングについて -- たとえば、surrogatesbyte order marks(BOMs) -- もっと知りたければ perlunicode を 見て下さい。

Perl の Unicode サポート

Starting from Perl 5.6.0, Perl has had the capacity to handle Unicode natively. Perl 5.8.0, however, is the first recommended release for serious Unicode work. The maintenance release 5.6.1 fixed many of the problems of the initial Unicode implementation, but for example regular expressions still do not work with Unicode in 5.6.1.

Perl 5.6.0 から、Perl は、Unicode をネイティブに扱う能力を持っていました。 しかし、Perl 5.8.0 の最初の RC リリースは、重大な Unicode の仕事です。 メンテナンスリリースの 5.6.1 は、最初の Unicode 実装の多くの問題を 修正しました。 ですが、たとえば、5.6.1 で、Unicode での正規表現はまだ働きません。

Starting from Perl 5.8.0, the use of use utf8 is needed only in much more restricted circumstances. In earlier releases the utf8 pragma was used to declare that operations in the current block or file would be Unicode-aware. This model was found to be wrong, or at least clumsy: the "Unicodeness" is now carried with the data, instead of being attached to the operations. Only one case remains where an explicit use utf8 is needed: if your Perl script itself is encoded in UTF-8, you can use UTF-8 in your identifier names, and in string and regular expression literals, by saying use utf8. This is not the default because scripts with legacy 8-bit data in them would break. See utf8.

Perl 5.8.0 から、use utf8 の使用は、遥かに限られた状況でのみ 必要になりました。 初期のリリースでは、utf8 プラグマは、現在のブロックやファイルの操作が、 Unicode であると明示するのを宣言するために使われました。 このモデルは間違いが見つけられるか、少なくとも、不格好です: 操作に添付するかわりに、"Unicodeness" は、今や、データに持ち込まれています。 唯一残されている、明示的に use utf8 をする必要がある場所は: Perl スクリプト自身が UTF-8 でエンコードされていれば、 識別子の名前、文字の中と、正規表現のリテラルに、UTF-8 を使うことができます。 これは、デフォルトではありません。 なぜなら、レガシーの 8-bit データのスクリプトが壊れるからです。 utf8 を参照してください。

Perl の Unicode モデル

Perl supports both pre-5.6 strings of eight-bit native bytes, and strings of Unicode characters. The principle is that Perl tries to keep its data as eight-bit bytes for as long as possible, but as soon as Unicodeness cannot be avoided, the data is transparently upgraded to Unicode.

Perl は、Perl 5.6 より前での 8 ビットネイティブのバイト列の文字列と、 Unicode 文字の文字列の両方をサポートします。 方針は、Perl は、可能な限り長く 8 ビットバイト列としてデータを 保とうとします。 ですが、Unicode 性が避けられなくなった時点で、 データは透過的に Unicode に昇格されます。

Internally, Perl currently uses either whatever the native eight-bit character set of the platform (for example Latin-1) is, defaulting to UTF-8, to encode Unicode strings. Specifically, if all code points in the string are 0xFF or less, Perl uses the native eight-bit character set. Otherwise, it uses UTF-8.

内部的には、Perl は、プラットフォームの 8 ビット文字セット (例えば、Latin-1)は、デフォルトは UTF-8 ですが、Unicode 文字列に エンコードします。 特に、文字列中の、全てのコードポイントは、0xFF 以下であれば、 Perl は、ネイティブの 8 ビットの文字セットを使います。 そうでなければ、UTF-8 を使います。

A user of Perl does not normally need to know nor care how Perl happens to encode its internal strings, but it becomes relevant when outputting Unicode strings to a stream without a PerlIO layer -- one with the "default" encoding. In such a case, the raw bytes used internally (the native character set or UTF-8, as appropriate for each string) will be used, and a "Wide character" warning will be issued if those strings contain a character beyond 0x00FF.

Perlのユーザは普通は、Perl がその内部文字列をたまたま、どのように エンコードするかを、知る必要も、気にする必要もありませんが、Unicode 文字列を PerlIO 層なしに -- 「デフォルトの」エンコーディングで -- ストリームに 出力しようとすると、関係するようになります。 このようなケースでは、内部的に使われている生のバイト列(それぞれの 文字列の必要に応じて、ネイティブの文字セットか、UTF-8)が使われます。 それらの文字列に、0x00FF を超える文字があれば、"Wide character" の警告が 出されます。

For example,

たとえば、

      perl -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"'

produces a fairly useless mixture of native bytes and UTF-8, as well as a warning:

ネイティブのバイト列と UTF-8 の、まったく役に立たない混合もまた、 同様に警告を出します:

     Wide character in print at ...

To output UTF-8, use the :encoding or :utf8 output layer. Prepending

UTF-8 を出力するために、:encoding:utf8 出力層を使います。 先頭にこれを追加することで:

      binmode(STDOUT, ":utf8");

to this sample program ensures that the output is completely UTF-8, and removes the program's warning.

このサンプルプログラムが、出力が完全に UTF-8 であることを保証し、 プログラムの警告を削除します。

You can enable automatic UTF-8-ification of your standard file handles, default open() layer, and @ARGV by using either the -C command line switch or the PERL_UNICODE environment variable, see perlrun for the documentation of the -C switch.

-C コマンドラインスイッチか、PERL_UNICODE 環境変数のどちらか一方を 使うことで、標準ファイルハンドルと、デフォルトの open() 層と、 @ARGV の UTF-8 化を自動的に有効に出来ます; perlrun-C スイッチのドキュメントを見て下さい。

Note that this means that Perl expects other software to work, too: if Perl has been led to believe that STDIN should be UTF-8, but then STDIN coming in from another command is not UTF-8, Perl will complain about the malformed UTF-8.

このことは、Perl が他のソフトウェアの動きを予測することを意味するのに 気をつけて下さい: Perl が STDIN が UTF-8 であるべきと信じるように主導されていて、 他のコマンドからくる STDIN が UTF-8 でなければ、 Perl は、不正な UTF-8 であると文句を言います。

All features that combine Unicode and I/O also require using the new PerlIO feature. Almost all Perl 5.8 platforms do use PerlIO, though: you can see whether yours is by running "perl -V" and looking for useperlio=define.

Unicode と、I/O の結合の特徴もまた、新しい PerlIO の特徴を使うことを 必要とします。 ほとんど全ての Perl5.8 プラットフォームは、PerlIO を使います。 ですが: "perl -V" を動かして、useperlio=define を見れば、PerlIO を 使っているかどうか、わかります。

Unicode と EBCDIC

Perl 5.8.0 also supports Unicode on EBCDIC platforms. There, Unicode support is somewhat more complex to implement since additional conversions are needed at every step. Some problems remain, see perlebcdic for details.

Perl 5.8.0 は、EBCDIC プラットフォームでもまた、Unicode をサポートします。 ここでは、各ステップで追加の変換が必要になるので、Unicode サポートは 実装が若干より複雑になります。 いくつかの問題が残っています; 詳しくは perlebcdic を参照してください。

In any case, the Unicode support on EBCDIC platforms is better than in the 5.6 series, which didn't work much at all for EBCDIC platform. On EBCDIC platforms, the internal Unicode encoding form is UTF-EBCDIC instead of UTF-8. The difference is that as UTF-8 is "ASCII-safe" in that ASCII characters encode to UTF-8 as-is, while UTF-EBCDIC is "EBCDIC-safe".

ともかく、EBCDIC プラットフォームでの Unicode 対応は、EBCDIC プラットフォームではうまく動かなかった 5.6 シリーズよりは改善しています。 EBCDIC プラットフォームでは、内部 Unicode エンコーディング形式は UTF-8 ではなく UTF-EBCDIC です。 この違いは、ASCII 文字はそのまま UTF-8 にエンコードされるという点において "ASCII セーフ" ですが、一方 UTF-EBCDIC は "EBCDIC セーフ" です。

Unicode の作成

To create Unicode characters in literals for code points above 0xFF, use the \x{...} notation in double-quoted strings:

0xFF を超えるコードポイントのリテラルで Unicode 文字を作るためには、 \x{...} 記法をダブルクォートされた文字列の中で使います。

    my $smiley = "\x{263a}";

Similarly, it can be used in regular expression literals

同様に、正規表現の中でも使えます。

    $smiley =~ /\x{263a}/;

At run-time you can use chr():

chr() を使って、実行時に:

    my $hebrew_alef = chr(0x05d0);

See "Further Resources" for how to find all these numeric codes.

全てのこれらの数字のコードを見つける方法は、"Further Resources" を 参照してください。

Naturally, ord() will do the reverse: it turns a character into a code point.

当然、ord() は、逆を行います: 文字をコードポイントに変えます。

Note that \x.. (no {} and only two hexadecimal digits), \x{...}, and chr(...) for arguments less than 0x100 (decimal 256) generate an eight-bit character for backward compatibility with older Perls. For arguments of 0x100 or more, Unicode characters are always produced. If you want to force the production of Unicode characters regardless of the numeric value, use pack("U", ...) instead of \x.., \x{...}, or chr().

0x100(10 進の 256)未満の引数の、\x.. ({} なしで、 2 つの 16 進数の数字のみです)と、\x{...} と、chr(...) は、古い Perl との互換性のために、8 ビットの文字列を生成します。 x100 かそれ以上の引数では、常に Unicode 文字が生成されます。 何が何でも、数字の値の Unicode 文字を、強制的に生成したければ、 \x..\x{...}chr() の代わりに、pack("U", ...) を使って下さい。

You can also use the charnames pragma to invoke characters by name in double-quoted strings:

ダブルクォートされた文字列内で、名前で文字を呼び出すために、 charnames プラグマを使うこともできます:

    use charnames ':full';
    my $arabic_alef = "\N{ARABIC LETTER ALEF}";

And, as mentioned above, you can also pack() numbers into Unicode characters:

そして、上述のように、数字を Unicode 文字に、pack() できます:

   my $georgian_an  = pack("U", 0x10a0);

Note that both \x{...} and \N{...} are compile-time string constants: you cannot use variables in them. if you want similar run-time functionality, use chr() and charnames::vianame().

\x{...} と、\N{...} の両方は、コンパイル時の文字列定数です: その中に変数を使うことはできません。 類似のことを実行時にしたいなら、c<chr()> と、charnames::vianame() を 使ってください。

If you want to force the result to Unicode characters, use the special "U0" prefix. It consumes no arguments but causes the following bytes to be interpreted as the UTF-8 encoding of Unicode characters:

結果を Unicode 文字に強制したいなら、特別な、"U0" 接頭辞を使って下さい。 これは引数を消費しませんが、引き続くバイト列を Unicode 文字の UTF-8 エンコーディングとして解釈させます:

   my $chars = pack("U0W*", 0x80, 0x42);

Likewise, you can stop such UTF-8 interpretation by using the special "C0" prefix.

同様に、特殊な "C0" 接頭辞を使うことによって、このような UTF-8 の解釈を 停止させることができます。

Unicode を扱う

Handling Unicode is for the most part transparent: just use the strings as usual. Functions like index(), length(), and substr() will work on the Unicode characters; regular expressions will work on the Unicode characters (see perlunicode and perlretut).

Unicode を扱うことは、多くの部分にとって、透過的です: 文字列をいつものように使うだけです。 index()length()substr() のような関数は Unicode 文字列で 動きます; 正規表現も Unicode 文字列で動きます(perlunicodeperlretut を 参照してください)。

Note that Perl considers combining character sequences to be separate characters, so for example

Perl は combining character sequences を別々の文字と考えていることに 注意して下さい。 ですので、例えば

    use charnames ':full';
    print length("\N{LATIN CAPITAL LETTER A}\N{COMBINING ACUTE ACCENT}"), "\n";

will print 2, not 1. The only exception is that regular expressions have \X for matching a combining character sequence.

これは 1 ではなく、2 を表示します。 唯一の例外は、正規表現に、combining character sequence に マッチするために、\X がある場合です。

Life is not quite so transparent, however, when working with legacy encodings, I/O, and certain special cases:

しかし、レガシーエンコーディング、I/O、そしてある種の特殊な状況では、 人生はそれほど透過的ではありません:

レガシーエンコーディング

When you combine legacy data and Unicode the legacy data needs to be upgraded to Unicode. Normally ISO 8859-1 (or EBCDIC, if applicable) is assumed.

レガシーデータと Unicode とを組み合わせる時は、 レガシーデータを Unicode に昇格しなければなりません。 通常、ISO 8859-1 (か、必要なら EBCDIC)が仮定されます。

The Encode module knows about many encodings and has interfaces for doing conversions between those encodings:

Encode モジュールは多くのエンコーディングを知っており、 それらのエンコーディングの間の変換をするインターフェースを持っています。

    use Encode 'decode';
    $data = decode("iso-8859-3", $data); # convert from legacy to utf-8

Unicode I/O

Normally, writing out Unicode data

通常、Unicode データを書き出すことは、

    print FH $some_string_with_unicode, "\n";

produces raw bytes that Perl happens to use to internally encode the Unicode string. Perl's internal encoding depends on the system as well as what characters happen to be in the string at the time. If any of the characters are at code points 0x100 or above, you will get a warning. To ensure that the output is explicitly rendered in the encoding you desire--and to avoid the warning--open the stream with the desired encoding. Some examples:

Unicode 文字列を内部的にエンコードするのにたまたまつかわれている、 生のバイト列を生成することです。 Perl の内部エンコーディングは、そのときに、文字列にたまたまある文字と 同じように、システム依存です。 どの文字も、コードポイントが 0x100 以上なら、警告がでます。 出力が明示的に、望んでいるエンコーディングにレンダリングされていることを 保証し、警告を避けるために、望んでいるエンコーディングでストリームを open してください。 いくつか例示します:

    open FH, ">:utf8", "file";

    open FH, ">:encoding(ucs2)",      "file";
    open FH, ">:encoding(UTF-8)",     "file";
    open FH, ">:encoding(shift_jis)", "file";

and on already open streams, use binmode():

すでに開かれているストリームに関しては、binmode() を使います:

    binmode(STDOUT, ":utf8");

    binmode(STDOUT, ":encoding(ucs2)");
    binmode(STDOUT, ":encoding(UTF-8)");
    binmode(STDOUT, ":encoding(shift_jis)");

The matching of encoding names is loose: case does not matter, and many encodings have several aliases. Note that the :utf8 layer must always be specified exactly like that; it is not subject to the loose matching of encoding names. Also note that :utf8 is unsafe for input, because it accepts the data without validating that it is indeed valid UTF8.

エンコーディング名のマッチングはルーズです: 大文字小文字は重要ではなく、 多くのエンコーディングでは、いくつかの別名があります。 :utf8 層は、常に、きっちりとそのように指定される必要があります。 このことは、エンコーディング名のルーズなマッチングの対象では ありません。 データが妥当な UTF8 であるかどうかを検証せずに受け入れるので、入力に 対しては :utf8 は安全ではないことにも注意してください。

See PerlIO for the :utf8 layer, PerlIO::encoding and Encode::PerlIO for the :encoding() layer, and Encode::Supported for many encodings supported by the Encode module.

:utf8 層に関しては、PerlIO を参照してください; :encoding() に関しては、Encode::PerlIO を参照してください; Encode モジュールでサポートされている、多くのエンコーディングに関しては、 Encode::Supported を参照してください。

Reading in a file that you know happens to be encoded in one of the Unicode or legacy encodings does not magically turn the data into Unicode in Perl's eyes. To do that, specify the appropriate layer when opening files

Unicode かレガシーのエンコーディングどちらかでたまたまエンコードされている ファイルを読み込んでも、Perl の目で、魔法のように、データが Unicode に 変わったりしません。 そうするためには、ファイルを開くときに、適切な層を指定します。

    open(my $fh,'<:encoding(utf8)', 'anything');
    my $line_of_unicode = <$fh>;

    open(my $fh,'<:encoding(Big5)', 'anything');
    my $line_of_unicode = <$fh>;

The I/O layers can also be specified more flexibly with the open pragma. See open, or look at the following example.

I/O 層は、もっと柔軟に、open プラグマでもまた、指定することが出来ます。 open を参照するか、次の例を見て下さい。

    use open ':encoding(utf8)'; # input/output default encoding will be UTF-8
    open X, ">file";
    print X chr(0x100), "\n";
    close X;
    open Y, "<file";
    printf "%#x\n", ord(<Y>); # this should print 0x100
    close Y;

With the open pragma you can use the :locale layer

open プラグマで、:local 層も使えます:

    BEGIN { $ENV{LC_ALL} = $ENV{LANG} = 'ru_RU.KOI8-R' }
    # the :locale will probe the locale environment variables like LC_ALL
    use open OUT => ':locale'; # russki parusski
    open(O, ">koi8");
    print O chr(0x430); # Unicode CYRILLIC SMALL LETTER A = KOI8-R 0xc1
    close O;
    open(I, "<koi8");
    printf "%#x\n", ord(<I>), "\n"; # this should print 0xc1
    close I;

These methods install a transparent filter on the I/O stream that converts data from the specified encoding when it is read in from the stream. The result is always Unicode.

ストリームからファイルが読まれるときに、特定のエンコーディングから、 データを変換する I/O ストリーム上の透過的な層です。 その結果は常に Unicode です。

The open pragma affects all the open() calls after the pragma by setting default layers. If you want to affect only certain streams, use explicit layers directly in the open() call.

open プラグマは、デフォルトの層を設定することで、プラグマの後の 全ての open() 呼び出しに影響します。 あるストリームだけに影響を限定したいなら、open() 呼び出しで明示的な 層を使って下さい。

You can switch encodings on an already opened stream by using binmode(); see "binmode" in perlfunc.

binmode() を使って、すでに開かれているストリームのエンコーディングを 変えることが出来ます; "binmode" in perlfunc を参照してください。

The :locale does not currently (as of Perl 5.8.0) work with open() and binmode(), only with the open pragma. The :utf8 and :encoding(...) methods do work with all of open(), binmode(), and the open pragma.

:locale は、現在(Perl 5.8.0 の時点で)、open()binmode() では 動きません。 open プラグマでのみ動きます。 :utf8:encoding(...) メソッドは、全ての open()binmode()open プラグマで動きます。

Similarly, you may use these I/O layers on output streams to automatically convert Unicode to the specified encoding when it is written to the stream. For example, the following snippet copies the contents of the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to the file "text.utf8", encoded as UTF-8:

似たようなものに、ストリームに書き出すときに、自動的に Unicode を 特定のエンコーディングに変換する、出力ストリームの I/O 層を使うかも 知れません。 例えば、次のようなコードの断片は、(ISO-2022-JP, またの名を JIS として エンコードされている)" text.jis" ファイルの内容を、UTF-8 として エンコードされる "text.utf8" ファイルにコピーします。

    open(my $nihongo, '<:encoding(iso-2022-jp)', 'text.jis');
    open(my $unicode, '>:utf8',                  'text.utf8');
    while (<$nihongo>) { print $unicode $_ }

The naming of encodings, both by the open() and by the open pragma allows for flexible names: koi8-r and KOI8R will both be understood.

open() と、open プラグマの両方で使われているエンコーディングの 名前は、フレキシブルな名前でも使えます: koi8-rと、KOI8R は、 両方とも理解されます。

Common encodings recognized by ISO, MIME, IANA, and various other standardisation organisations are recognised; for a more detailed list see Encode::Supported.

ISO、MIME、IANA、様々な他の標準化機関が認識している、一般的な エンコーディングが認識されます; より詳細なリストは、 Encode::Supported を参照してください。

read() reads characters and returns the number of characters. seek() and tell() operate on byte counts, as do sysread() and sysseek().

read() は、文字を読み、文字の数を返します。 seek()tell() は、バイトカウントに関して操作します。 sysreadsysseek() も同様です。

Notice that because of the default behaviour of not doing any conversion upon input if there is no default layer, it is easy to mistakenly write code that keeps on expanding a file by repeatedly encoding the data:

デフォルト層がなければ、入力になんの変換もしないのがデフォルトの 振る舞いなので、繰り返しデータをエンコーディングすることで、 ファイルを展開し続けるコードを誤って書きやすいです。

    # BAD CODE WARNING
    open F, "file";
    local $/; ## read in the whole file of 8-bit characters
    $t = <F>;
    close F;
    open F, ">:encoding(utf8)", "file";
    print F $t; ## convert to UTF-8 on output
    close F;

If you run this code twice, the contents of the file will be twice UTF-8 encoded. A use open ':encoding(utf8)' would have avoided the bug, or explicitly opening also the file for input as UTF-8.

このコードを 2 回実行すると、file の内容は、UTF-8 に、2 回 エンコードされます。 use open 'encoding(utf8)' は、バグを避けるでしょう; もしくは、UTF-8 として入力するために、File を、明示的に開くことです。

NOTE: the :utf8 and :encoding features work only if your Perl has been built with the new PerlIO feature (which is the default on most systems).

注意: :utf8:encoding の機能は、Perl が新しい PerlIO の機能で ビルドされている場合(ほとんどのシステムで、それがデフォルトです)にのみ 動作します。

Unicode をテキストとして表示する

Sometimes you might want to display Perl scalars containing Unicode as simple ASCII (or EBCDIC) text. The following subroutine converts its argument so that Unicode characters with code points greater than 255 are displayed as \x{...}, control characters (like \n) are displayed as \x.., and the rest of the characters as themselves:

Unicode を含んでいる Perl のスカラを、単純な ASCII(か、EBCDIC)の テキストとして、表示したいかもしれません。 下のサブルーチンは、引数を変換して、255 より大きいコードポイントの Unicode 文字を、\x{...} として表示し、(\n のような)制御文字は、 \x.. として表示します。 残りの文字は、そのまま表示します:

   sub nice_string {
       join("",
         map { $_ > 255 ?                  # if wide character...
               sprintf("\\x{%04X}", $_) :  # \x{...}
               chr($_) =~ /[[:cntrl:]]/ ?  # else if control character ...
               sprintf("\\x%02X", $_) :    # \x..
               quotemeta(chr($_))          # else quoted or as themselves
         } unpack("W*", $_[0]));           # unpack Unicode characters
   }

For example,

たとえば、

   nice_string("foo\x{100}bar\n")

returns the string

は、次のような文字列になり:

   'foo\x{0100}bar\x0A'

which is ready to be printed.

表示可能になります。

特殊な状況

  • Bit Complement Operator ~ And vec()

    演算子 ~ と、vec() についてのちょっとした補足

    The bit complement operator ~ may produce surprising results if used on strings containing characters with ordinal values above 255. In such a case, the results are consistent with the internal encoding of the characters, but not with much else. So don't do that. Similarly for vec(): you will be operating on the internally-encoded bit patterns of the Unicode characters, not on the code point values, which is very probably not what you want.

    演算子 ~ は、255 を超える序数の値の文字を含んでいる文字列で、 使われると、驚くべき結果になるでしょう。 そのようなケースでは、その結果は文字の内部的なエンコーディングで一貫性が あります。 しかし、他の多くでは違います。 ですので、そのようなことはしないでください。 vec() も同様です: コードポイントの値ではなく、内部的にエンコードされた、 Unicode 文字列のビットパターンを操作することになります; おそらく、それは望んだことではないでしょう。

  • Peeking At Perl's Internal Encoding

    Perl の内部エンコーディングをのぞき見る

    Normal users of Perl should never care how Perl encodes any particular Unicode string (because the normal ways to get at the contents of a string with Unicode--via input and output--should always be via explicitly-defined I/O layers). But if you must, there are two ways of looking behind the scenes.

    Perl がどのように、特定の Unicode 文字列をエンコードしているかを、 Perl の普通のユーザは気にするべきではありません (Unicode で文字列の内容に達する普通の方法 -- 入出力によって -- は、常に 明示的に定義された I/O 層を経由すべきだからです)。 ですが、もし必要なら、隠れている裏側を見る 2 つの方法があります。

    One way of peeking inside the internal encoding of Unicode characters is to use unpack("C*", ... to get the bytes of whatever the string encoding happens to be, or unpack("U0..", ...) to get the bytes of the UTF-8 encoding:

    Unicode 文字の内部エンコーディングの内側を覗き見る方法の 1 つは、 エンコーディングが何であろうとも文字列のバイト列を得るために unpack("C*", ... を使うか、UTF-8 エンコーディングのバイト列を得るために unpack("U0..", ...) を使うことです:

        # this prints  c4 80  for the UTF-8 bytes 0xc4 0x80
        print join(" ", unpack("U0(H2)*", pack("U", 0x100))), "\n";

    Yet another way would be to use the Devel::Peek module:

    もう一つの方法は、Dvel::Peek モジュールを使うことです:

        perl -MDevel::Peek -e 'Dump(chr(0x100))'

    That shows the UTF8 flag in FLAGS and both the UTF-8 bytes and Unicode characters in PV. See also later in this document the discussion about the utf8::is_utf8() function.

    これは、FLAGS の UTF8 フラグと、UTF-8 バイトと、PV の中の Unicode 文字の両方を見せます。 このドキュメントの後にある、utf8::is_utf8() 機能についての議論も 参照してください。

発展した話題

  • String Equivalence

    文字列の等価性

    The question of string equivalence turns somewhat complicated in Unicode: what do you mean by "equal"?

    文字列の等価性の疑問は、Unicode でいくぶん複雑になります。 "等価" で、何を意味していますか?

    (Is LATIN CAPITAL LETTER A WITH ACUTE equal to LATIN CAPITAL LETTER A?)

    (IS LATIN CAPITAL LETTER A WITH ACCUTELATIN CAPITAL LETTER Aは、等しいでしょうか?)

    The short answer is that by default Perl compares equivalence (eq, ne) based only on code points of the characters. In the above case, the answer is no (because 0x00C1 != 0x0041). But sometimes, any CAPITAL LETTER As should be considered equal, or even As of any case.

    短く答えれば次のようになります。 デフォルトでは、Perl は(eq と、ne で)等価性を 比較しますが、これらは、文字のコードポイントでのみに基づいています。 上のケースでは、答えはいいえです(0x00C1 != 0x0041 ですから)。 しかし、どんな CAPITAL LETTER A も等しいと考えるべき時や、大文字小文字に 関わらずどんな A も等しいと考えるべき時もあります。

    The long answer is that you need to consider character normalization and casing issues: see Unicode::Normalize, Unicode Technical Reports #15 and #21, Unicode Normalization Forms and Case Mappings, http://www.unicode.org/unicode/reports/tr15/ and http://www.unicode.org/unicode/reports/tr21/

    長く答えるなら、文字の正規化と大文字小文字の問題を考える必要があります: Unicode::Normalize、Unicode テクニカルレポート #15 と #21 である Unicodde Normalization FormsCase Mappingshttp://www.unicode.org/unicode/reports/tr15/http://www.unicode.org/unicode/reports/tr21/ を参照してください。

    As of Perl 5.8.0, the "Full" case-folding of Case Mappings/SpecialCasing is implemented.

    Perl 5.8.0 から、Case Mappings/SpecialCasing の、 "Full" ケースフォールディングが実装されています。

  • String Collation

    文字列の照合(Collation)

    People like to see their strings nicely sorted--or as Unicode parlance goes, collated. But again, what do you mean by collate?

    文字列がうまくソートされている(あるいは Unicode の業界用語を使えば、 照合されている(collated))のを好みます。 ですが、再び、照合で何を意味していますか?

    (Does LATIN CAPITAL LETTER A WITH ACUTE come before or after LATIN CAPITAL LETTER A WITH GRAVE?)

    (LATIN CAPITAL LETTER A WITH ACUTE は、 LATIN CAPITAL LETTER A WITH GRAVE より、 前でしょうか後でしょうか?)

    The short answer is that by default, Perl compares strings (lt, le, cmp, ge, gt) based only on the code points of the characters. In the above case, the answer is "after", since 0x00C1 > 0x00C0.

    短く答えれば次のようになります。 Perl は、文字列を、(ltlecmpgegt)で比較しますが、 これらは、文字のコードポイントでのみに基づいています。 上のケースでは、答えは、0x00C1 > 0x00C0 ですので、"後"になります。

    The long answer is that "it depends", and a good answer cannot be given without knowing (at the very least) the language context. See Unicode::Collate, and Unicode Collation Algorithm http://www.unicode.org/unicode/reports/tr10/

    長く答えるなら、「場合によります」; 良い答えは、(とても少なくとも)言語のコンテキストを知らずには、 与えられません。 Unicode::Collate, Unicode Collation Algorithm http://www.unicode.org/unicode/reports/tr10/ を参照してください。

その他

  • Character Ranges and Classes

    文字の範囲とクラス

    Character ranges in regular expression character classes (/[a-z]/) and in the tr/// (also known as y///) operator are not magically Unicode-aware. What this means is that [A-Za-z] will not magically start to mean "all alphabetic letters"; not that it does mean that even for 8-bit characters, you should be using /[[:alpha:]]/ in that case.

    正規表現の文字クラス(/[a-z]/)内と、tr///(y/// としても知られる) 演算子内では、自動的には Unicode 対応にはなりません。 これが意味することは、[A-Za-z] は、自動的に "全てのアルファベット文字"を 意味するようにはなりません; 8 ビットの文字で意味します; このケースでは、/[[:alpha:]]/ を使うべきです。

    For specifying character classes like that in regular expressions, you can use the various Unicode properties--\pL, or perhaps \p{Alphabetic}, in this particular case. You can use Unicode code points as the end points of character ranges, but there is no magic associated with specifying a certain range. For further information--there are dozens of Unicode character classes--see perlunicode.

    正規表現内のこのような特定の文字クラスに、様々な Unicode プロパティ -- \pL、または、この特別なケースでは、たぶん、\p{Alphabetic} を 使うことができます。 文字の範囲の終わりのポイントとして、Unicode のコードポイントを 使うことが出来ます。 ですが、ある範囲を特定するのに結びつける何の魔法もありません。 詳しいことは--数ダースの Unicode 文字クラスがあります-- perlunicode を見て下さい。

  • String-To-Number Conversions

    文字列から数字への変換

    Unicode does define several other decimal--and numeric--characters besides the familiar 0 to 9, such as the Arabic and Indic digits. Perl does not support string-to-number conversion for digits other than ASCII 0 to 9 (and ASCII a to f for hexadecimal).

    Unicode は、なじみのある、アラビアやインドの数字のような 0 から 9 に加えて、 複数の他の 10 進数--と数字の--文字を、定義します。 Perl は、ASCII の 0 から 9(と、16 進法の ASCII の a から f)以外の数字の、 文字列から数への変換をサポートしません。

質問と回答

  • Will My Old Scripts Break?

    古いスクリプトは壊れるでしょうか?

    Very probably not. Unless you are generating Unicode characters somehow, old behaviour should be preserved. About the only behaviour that has changed and which could start generating Unicode is the old behaviour of chr() where supplying an argument more than 255 produced a character modulo 255. chr(300), for example, was equal to chr(45) or "-" (in ASCII), now it is LATIN CAPITAL LETTER I WITH BREVE.

    たぶん、壊れません。 どうにかして、Unicode 文字を生成していなければ、古い挙動は保護されます。 振る舞いが変更され、Unicode を生成し始める唯一のものは、古い chr() は 引数として 255 を超える値が指定されると、255 を法とした文字が生成される というものです。 例えば、chr(300) は、chr(45) あるいは (ASCII の)"-" と同じでした。 現在ではそれは、LATIN CAPITAL LETTER I WITH BREVE です。

  • How Do I Make My Scripts Work With Unicode?

    私のスクリプトを Unicode で動かすには?

    Very little work should be needed since nothing changes until you generate Unicode data. The most important thing is getting input as Unicode; for that, see the earlier I/O discussion.

    Unicode データを生成するまで、ほとんど何もする必要はありません。 もっとも重要なものは、Unicode として、入力を得ることです; なので、以前の I/O の議論を見て下さい。

  • How Do I Know Whether My String Is In Unicode?

    Unicode の文字列かどうかを知るには?

    You shouldn't have to care. But you may, because currently the semantics of the characters whose ordinals are in the range 128 to 255 is different depending on whether the string they are contained within is in Unicode or not. (See perlunicode.)

    気にする必要はないはずです。 しかし、今のところ範囲 128 から 256 の文字の意味論は、文字列が Unicode で 保管されているかどうかによって異なるため、知りたいかもしれません。 (perlunicode を参照してください。)

    To determine if a string is in Unicode, use:

    文字列が Unicode かどうかを決定するには、以下を使います:

        print utf8::is_utf8($string) ? 1 : 0, "\n";

    But note that this doesn't mean that any of the characters in the string are necessary UTF-8 encoded, or that any of the characters have code points greater than 0xFF (255) or even 0x80 (128), or that the string has any characters at all. All the is_utf8() does is to return the value of the internal "utf8ness" flag attached to the $string. If the flag is off, the bytes in the scalar are interpreted as a single byte encoding. If the flag is on, the bytes in the scalar are interpreted as the (multi-byte, variable-length) UTF-8 encoded code points of the characters. Bytes added to an UTF-8 encoded string are automatically upgraded to UTF-8. If mixed non-UTF-8 and UTF-8 scalars are merged (double-quoted interpolation, explicit concatenation, and printf/sprintf parameter substitution), the result will be UTF-8 encoded as if copies of the byte strings were upgraded to UTF-8: for example,

    しかし、これは、文字列の文字のすべてが UTF-8 でエンコードされているとか、 文字のすべてが 0xFF(255)(あるいは 0x80(128)) より大きいコードポイントを 持つとか、文字列に文字が含まれているかとかいうことを 意味するわけではないことに注意してください。 is_utf8() がすることの全ては、$string につけられている内部の "utf8ness" フラグの値を返すことです。 フラグが無効であれば、スカラ内のバイト列は、シングルバイト エンコーディングとして解釈されます。 フラグが有効であれば、スカラ内のバイト列は、(マルチバイト、可変長の) UTF-8 でエンコードされた文字のコードポイントとして解釈されます。 (ダブルクオートされた語句、明示的な連結、printf/sprintf パラメタ 置換によって)非 UTF-8 と、UTF-8 のスカラがマージされた場合、この結果は、 バイト文字列のコピーが UTF-8 で昇格されたかのように、 UTF-8 でエンコードされています: 例えば、

        $a = "ab\x80c";
        $b = "\x{100}";
        print "$a = $b\n";

    the output string will be UTF-8-encoded ab\x80c = \x{100}\n, but $a will stay byte-encoded.

    出力する文字列は UTF-8 エンコードされた ab\x80c = \x{100}\n になりますが、 $a は、バイトエンコードされたままです。

    Sometimes you might really need to know the byte length of a string instead of the character length. For that use either the Encode::encode_utf8() function or the bytes pragma and the length() function:

    文字列の長さではなく、文字列のバイト長を知る必要があるかもしれません。 そのためには、Encode::encode_utf8() 関数か、bytes プラグマと length() 関数を使うだけです:

        my $unicode = chr(0x100);
        print length($unicode), "\n"; # will print 1
        require Encode;
        print length(Encode::encode_utf8($unicode)), "\n"; # will print 2
        use bytes;
        print length($unicode), "\n"; # will also print 2
                                      # (the 0xC4 0x80 of the UTF-8)
  • How Do I Detect Data That's Not Valid In a Particular Encoding?

    あるエンコーディングで、データが妥当でないことを検出するには?

    Use the Encode package to try converting it. For example,

    Encode パッケージを使って、それを変換してみてください。 例えば、

        use Encode 'decode_utf8';
    
        if (eval { decode_utf8($string, Encode::FB_CROAK); 1 }) {
            # $string is valid utf8
        } else {
            # $string is not valid utf8
        }

    Or use unpack to try decoding it:

    または unpack を使ってデコードしてみてください:

        use warnings;
        @chars = unpack("C0U*", $string_of_bytes_that_I_think_is_utf8);

    If invalid, a Malformed UTF-8 character warning is produced. The "C0" means "process the string character per character". Without that, the unpack("U*", ...) would work in U0 mode (the default if the format string starts with U) and it would return the bytes making up the UTF-8 encoding of the target string, something that will always work.

    妥当でなければ、Malformed UTF-8 character の警告が出ます。 "C0" は、「文字列を文字単位で処理する」ことを意味します。 それ以外では、unpack("U*", ...) は (フォーマット文字列が U で 始まっている場合のデフォルトである)U0 モードで動作し、ターゲット文字列の UTF08 エンコーディングでのバイト数を返し、このようなことは常に動作します。

  • How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa?

    バイナリデータを特定のエンコーディングに変換するには? また、その逆は?

    This probably isn't as useful as you might think. Normally, you shouldn't need to.

    たぶん、思うようには有益ではないでしょう。 ふつう、必要とするべきではありません。

    In one sense, what you are asking doesn't make much sense: encodings are for characters, and binary data are not "characters", so converting "data" into some encoding isn't meaningful unless you know in what character set and encoding the binary data is in, in which case it's not just binary data, now is it?

    ある意味では、あなたが尋ねようとしていることはほとんど意味はありません: エンコーディングは文字のためのもので、バイナリデータは「文字」ではないので、 「データ」を何かのエンコーディングに変換するということは、 バイナリデータの文字セットとエンコーディングが分かっていない限り無意味です; そして分かっているならそれは単なるバイナリデータではないですよね?

    If you have a raw sequence of bytes that you know should be interpreted via a particular encoding, you can use Encode:

    どのエンコーディングで解釈するべきか分かっている生のバイト列がある場合、 Encode が使えます:

        use Encode 'from_to';
        from_to($data, "iso-8859-1", "utf-8"); # from latin-1 to utf-8

    The call to from_to() changes the bytes in $data, but nothing material about the nature of the string has changed as far as Perl is concerned. Both before and after the call, the string $data contains just a bunch of 8-bit bytes. As far as Perl is concerned, the encoding of the string remains as "system-native 8-bit bytes".

    from_to() の呼び出しは $data のバイト列を変更しますが、Perl が 関知する限りにおいては文字列の性質は何も変わりません。 呼び出しの前後の両方において、文字列 $data は単に 8 ビットのバイトの 塊です。 Perl が関知するかぎりにおいては、文字列のエンコーディングは 「システムにネイティブな 8 ビットのバイト列」のままです。

    You might relate this to a fictional 'Translate' module:

    これを架空の 'Translate' モジュールと関連付けることもできます:

       use Translate;
       my $phrase = "Yes";
       Translate::from_to($phrase, 'english', 'deutsch');
       ## phrase now contains "Ja"

    The contents of the string changes, but not the nature of the string. Perl doesn't know any more after the call than before that the contents of the string indicates the affirmative.

    文字列の内容は変わりますが、文字列の性質は変わりません。 Perl は文字列の内容が肯定を意味するという呼び出し前の状態よりも多く、 呼び出しによって何かを知ることはありません。

    Back to converting data. If you have (or want) data in your system's native 8-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use pack/unpack to convert to/from Unicode.

    データの変換に戻ります。 もしシステムのネイティブな 8 ビットエンコーディング(例えば、Latin-1, EBCDIC など)のデータを持っている(あるいは欲しい)場合は、Unicode との変換に pack/unpack を使えます。

        $native_string  = pack("W*", unpack("U*", $Unicode_string));
        $Unicode_string = pack("U*", unpack("W*", $native_string));

    If you have a sequence of bytes you know is valid UTF-8, but Perl doesn't know it yet, you can make Perl a believer, too:

    あなたはバイト列が妥当な UTF-8 であると 分かっている けれども、Perl が 知らない場合、Perl に信じさせることもできます:

        use Encode 'decode_utf8';
        $Unicode = decode_utf8($bytes);

    or:

    または:

        $Unicode = pack("U0a*", $bytes);

    You can find the bytes that make up a UTF-8 sequence with

    UTF-8 シーケンスを作るバイト列は以下のようにして見つけられます

            @bytes = unpack("C*", $Unicode_string)

    and you can create well-formed Unicode with

    整形された Unicode は以下のようにして作成できます

            $Unicode_string = pack("U*", 0xff, ...)
  • How Do I Display Unicode? How Do I Input Unicode?

    Unicode を表示するには? Unicode を入力するには?

    http://www.alanwood.net/unicode/http://www.cl.cam.ac.uk/~mgk25/unicode.html を参照してください。

  • How Does Unicode Work With Traditional Locales?

    伝統的なロケールと Unicode は、どのように動きますか?

    In Perl, not very well. Avoid using locales through the locale pragma. Use only one or the other. But see perlrun for the description of the -C switch and its environment counterpart, $ENV{PERL_UNICODE} to see how to enable various Unicode features, for example by using locale settings.

    Perl では、あまりうまくありません。 locale プラグマでロケールを使うことを避けて下さい。 どちらか片方だけを使ってください。 しかし、-C スイッチと、それに対応する環境変数である $ENV{PERL_UNICODE} の説明のために、perlrun を参照してください; 様々な Unicode の機能が、どのように可能になっているのか、たとえば、 ロケールの設定によって、が、わかります。

16 進記法

The Unicode standard prefers using hexadecimal notation because that more clearly shows the division of Unicode into blocks of 256 characters. Hexadecimal is also simply shorter than decimal. You can use decimal notation, too, but learning to use hexadecimal just makes life easier with the Unicode standard. The U+HHHH notation uses hexadecimal, for example.

Unicode 標準は、16 進記法を使うのを好みます。 それは、256 の文字のブロックに Unicode を分割しているのが、 他の表記よりわかりやすいからです。 10 進記法を使うことも出来ますが、16 進記法を使うことを学べば、 Unicode 標準との暮らしが楽になります。 例えば、U+HHHH 表記は、16 進記法を使います。

The 0x prefix means a hexadecimal number, the digits are 0-9 and a-f (or A-F, case doesn't matter). Each hexadecimal digit represents four bits, or half a byte. print 0x..., "\n" will show a hexadecimal number in decimal, and printf "%x\n", $decimal will show a decimal number in hexadecimal. If you have just the "hex digits" of a hexadecimal number, you can use the hex() function.

0x の接頭辞は、16 進の数字を意味しています。 数字は、0-9 および a-f(か、A-F、大文字小文字は問いません)です。 それぞれの 16 進の数字は 4 ビット、1/2 バイトを表します。 print 0x..., "\n" は 16 進数を 10 進で見せます。 printf "%x\n", $decimal は 10 進数を 16 進で見せます。 "hex digits" の 16 進の数字があるなら、hex() 関数を使うことが出来ます。

    print 0x0009, "\n";    # 9
    print 0x000a, "\n";    # 10
    print 0x000f, "\n";    # 15
    print 0x0010, "\n";    # 16
    print 0x0011, "\n";    # 17
    print 0x0100, "\n";    # 256

    print 0x0041, "\n";    # 65

    printf "%x\n",  65;    # 41
    printf "%#x\n", 65;    # 0x41

    print hex("41"), "\n"; # 65

更なるリソース

  • Unicode Consortium

    http://www.unicode.org/

  • Unicode FAQ

    http://www.unicode.org/unicode/faq/

  • Unicode Glossary

    http://www.unicode.org/glossary/

  • Unicode Useful Resources

    http://www.unicode.org/unicode/onlinedat/resources.html

  • Unicode and Multilingual Support in HTML, Fonts, Web Browsers and Other Applications

    http://www.alanwood.net/unicode/

  • UTF-8 and Unicode FAQ for Unix/Linux

    http://www.cl.cam.ac.uk/~mgk25/unicode.html

  • Legacy Character Sets

    http://www.czyborra.com/ http://www.eki.ee/letter/

  • The Unicode support files live within the Perl installation in the directory

    Unicode サポートのファイルは、Perl をインストールしたディレクトリ内に あります;

        $Config{installprivlib}/unicore

    in Perl 5.8.0 or newer, and

    Perl 5.8.0 以上ではここです;

        $Config{installprivlib}/unicode

    in the Perl 5.6 series. (The renaming to lib/unicore was done to avoid naming conflicts with lib/Unicode in case-insensitive filesystems.) The main Unicode data file is UnicodeData.txt (or Unicode.301 in Perl 5.6.1.) You can find the $Config{installprivlib} by

    Perl 5.6 シリーズではここです。 (大文字小文字を区別しないファイルシステムでは、lib/Unicode との名前の衝突を 避けるために、lib/unicore にリネームされています。) メインの Unicode データファイルは、UnicodeData.txt(か、Perl 5.6.1 の Unicode.301)です。 次のようにして、$Config{installprivlib} を見つけることができます。

        perl "-V:installprivlib"

    You can explore various information from the Unicode data files using the Unicode::UCD module.

    Unicode::UCD モジュールを使って、Unicode データファイルから 様々な情報を調べることができます。

古い Perl での Unicode

If you cannot upgrade your Perl to 5.8.0 or later, you can still do some Unicode processing by using the modules Unicode::String, Unicode::Map8, and Unicode::Map, available from CPAN. If you have the GNU recode installed, you can also use the Perl front-end Convert::Recode for character conversions.

Perl 5.8.0 以降にアップグレード出来なくても、まだ、CPAN から利用できる、 Unicode::StringUnicode::Mmap8bUnicode::Map を使って、 いくつかの Unicode 処理ができます。 GNU recode がインストールされているなら、それの Perl フロントエンドである Convert::Recode を文字変換のために使えます。

The following are fast conversions from ISO 8859-1 (Latin-1) bytes to UTF-8 bytes and back, the code works even with older Perl 5 versions.

下記のものは、ISO 8859-1 (Latin-1) バイト列から UTF-8 バイト列に (あるいはその逆に)素早く変換するものです。 このコードは古い Perl 5 でも動きます。

    # ISO 8859-1 to UTF-8
    s/([\x80-\xFF])/chr(0xC0|ord($1)>>6).chr(0x80|ord($1)&0x3F)/eg;

    # UTF-8 to ISO 8859-1
    s/([\xC2\xC3])([\x80-\xBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg;

SEE ALSO

perlunitut, perlunicode, Encode, open, utf8, bytes, perlretut, perlrun, Unicode::Collate, Unicode::Normalize, Unicode::UCD

謝辞

Thanks to the kind readers of the perl5-porters@perl.org, perl-unicode@perl.org, linux-utf8@nl.linux.org, and unicore@unicode.org mailing lists for their valuable feedback.

著者、著作権、ライセンス

Copyright 2001-2002 Jarkko Hietaniemi <jhi@iki.fi>

This document may be distributed under the same terms as Perl itself.