5.20.1

名前

perluniintro - Perl Unicode introduction

perluniintro - Perl Unicode の手引き

説明

This document gives a general idea of Unicode and how to use Unicode in Perl. See "Further Resources" for references to more in-depth treatments of Unicode.

このドキュメントは、Unicode の一般的な考えと、 Perl で Unicode をどのように使うかを書いています。 Unicode のより深い扱いへのリファレンスについては "Further Resources" を 参照してください。

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 unify almost all other modern character set standards, covering more than 80 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 6.0 in October 2010.

Unicode と ISO/IEC 10646 は、ほとんど全ての現代の文字集合標準を統合し、 全ての商業的に重要な現代の言語を含む 80 以上の書記体系と数百以上の言語に 対応する組織的標準です。 もっとも大きい中国語、日本語、韓国語、それぞれの辞書の全ての文字もまた、 符号化されています。 この標準は、最終的には、250 の書記体系と、1000 以上の言語のほとんどすべての 文字を網羅する予定です。 Unicode 1.0 は 1991 年 10 月にリリースされ、Unicode 6.0 は 2010 年 10 月に リリースされました。

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. A code point is essentially the position of the character within the set of all possible Unicode characters, and thus in Perl, the term ordinal is often used interchangeably with it.

Unicode は、LATIN CAPITAL LETTER AGREEK SMALL LETTER ALPHA のような 文字と、その文字について固有の番号を定義します; この場合はそれぞれ、 0x0041 と 0x03B1 になります。 このような固有の番号は、符号位置 (code point) と呼ばれます。 符号位置は基本的には全ての Unicode 文字の集合の中の文字の位置なので、 Perl では、序数 (ordinal) がしばしば同じ意味として使われます。

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 進数字」、「句読点: のような、 様々な文字の 特性 (property) を定義します; これらの特性は、文字の名前と 独立です。 更に、様々な文字に対する、大文字化や小文字化や並び替えといった操作が 定義されています。

A Unicode logical "character" can actually consist of more than one internal actual "character" or code point. For Western languages, this is adequately modelled by 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. Some non-western languages require more complicated models, so Unicode created the grapheme cluster concept, which was later further refined into the extended grapheme cluster. For example, a Korean Hangul syllable is considered a single logical character, but most often consists of three actual Unicode characters: a leading consonant followed by an interior vowel followed by a trailing consonant.

Unicode 論理 「文字」は、実際には一つ以上の 実際 の「文字」または 符号位置から構成されます。 西洋の言語では、これは (LATIN CAPITAL LETTER A のような)、基底文字 (base character) に続いて、一つ以上の(COMBINING ACUTE ACCENT のような) 修飾字 (modifiers) によってモデル化されています。 この基底文字と修飾字の並びは、結合文字の並び (combining character sequence) と呼ばれます。 一部の非西洋言語ではより複雑なモデルが必要なので、Unicode は 書記素クラスタ (grapheme cluster) という概念を作成し、後に 拡張書記素クラスタ (extended grapheme cluster) という形に洗練させました。 例えば、ハングル音節文字は一つの論理文字として考えられますが、とても しばしば三つの実際の Unocde 文字から構成されています: 先頭子音に引き続いて内部母音、それに引き続いて末尾子音です。

Whether to call these extended grapheme clusters "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". However from the user's point of view, the whole sequence could be seen as one "character" since that's probably what it looks like in the context of the user's language. In this document, we take the programmer's point of view: one "character" is one Unicode code point.

これらの拡張書記素クラスタを「複数の文字」と呼ぶかどうかは、どのような 視点を取るかによります。 プログラマならば、おそらく、この順番のそれぞれの要素を、 1 つの単位、あるいは「文字」として、見ようとするでしょう。 しかし、ユーザの視点では、おそらくユーザの言語の文脈でみえるような ものなので、並び全体を一つの「文字」として見るでしょう。 この文書では、プログラマの視点を取ります: 一つの「文字」は一つの Unicode 符号位置です。

For some combinations of base character and modifiers, there are precomposed characters. There is a single character equivalent, for example, for the sequence LATIN CAPITAL LETTER A followed by COMBINING ACUTE ACCENT. It is called LATIN CAPITAL LETTER A WITH ACUTE. 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 ISO 8859). Using sequences, as Unicode does, allows for needing fewer basic building blocks (code points) to express many more potential grapheme clusters. To support conversion between equivalent forms, various normalization forms are also defined. Thus, LATIN CAPITAL LETTER A WITH ACUTE is in Normalization Form Composed, (abbreviated NFC), and the sequence LATIN CAPITAL LETTER A followed by COMBINING ACUTE ACCENT represents the same character in Normalization Form Decomposed (NFD).

一部の基底文字と修飾字の組み合わせは、合成済 (precomposed) 文字です。 例えば、LATIN CAPITAL LETTER A に引き続いて COMBINING ACUTE ACCENT の並びのように、等価な単一の文字があります。 これは LATIN CAPITAL LETTER A WITH ACUTE と呼ばれます。 しかし、これらの合成済文字は一部の組み合わせでのみ利用可能で、主に Unicode と(ISO 8859 のような)伝統的な標準との間の往復変換に対応するために あります。 Unicode がするように並びを使うと、より多くの潜在的な書記素クラスタを 表現するためにより少ない基本構築ブロック(符号位置)で済むようになります。 等価な形式の変換に対応するために、様々な 正規化形式 (normalization form) も定義されています。 従って、LATIN CAPITAL LETTER A WITH ACUTE正規化形式 C (Normalization Form Composed) (短縮形 NFC)にあり、 LATIN CAPITAL LETTER A に引き続いて COMBINING ACUTE ACCENT の並びは 正規化形式 D (Normalization Form Decomposed) (NFD) にある同じ文字を 表現します。

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 not also 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 のコントロール文字があり、それらは、本物の文字を 表現しません。

When Unicode was first conceived, it was thought that all the world's characters could be represented using a 16-bit word; that is a maximum of 0x10000 (or 65536) characters from 0x0000 to 0xFFFF would be needed. This soon proved to be false, and since Unicode 2.0 (July 1996), Unicode has been defined all the way up to 21 bits (0x10FFFF), and Unicode 3.1 (March 2001) defined the first characters above 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 が最初に着想されたとき、世界中の文字は 16 ビットで表現できると 考えられていました; 0x0000 から 0xFFFF までの最大 0x10000 (あるいは 65536) 文字が必要であるということです。 これは間違っているとすぐに証明され、Unicode 2.0(1996 年 7 月)から、Unicode は 21 ビット(0x10FFFF)まで、 様々に定義されています; Unicode 3.1(2001 年 3 月) では、0xFFFF を超えた 最初の文字が定義されました。 最初の 0x10000 文字は、Plane 0、または、基本多言語面 (Basic Multilingual Plane)(BMP) と呼ばれます。 Unicode 3.1 で、全部で 17(そう、17)の面が定義されました -- ですが、 まだ、定義された全文字のどこにも、まだ近くにありません。

When a new language is being encoded, Unicode generally will choose a block of consecutive unallocated code points for its characters. So far, the number of code points in these blocks has always been evenly divisible by 16. Extras in a block, not currently needed, are left unallocated, for future growth. But there have been occasions when a later release needed more code points than the available extras, and a new block had to allocated somewhere else, not contiguous to the initial one, to handle the overflow. Thus, it became apparent early on that "block" wasn't an adequate organizing principal, and so the Script property was created. (Later an improved script property was added as well, the Script_Extensions property.) Those code points that are in overflow blocks can still have the same script as the original ones. The script concept fits more closely with natural language: there is Latin script, Greek script, and so on; and there are several artificial scripts, like Common for characters that are used in multiple scripts, such as mathematical symbols. Scripts usually span varied parts of several blocks. For more information about scripts, see "Scripts" in perlunicode. The division into blocks exists, but it is almost completely accidental--an artifact of how the characters have been and still are allocated. (Note that this paragraph has oversimplified things for the sake of this being an introduction. Unicode doesn't really encode languages, but the writing systems for them--their scripts; and one script can be used by many languages. Unicode also encodes things that aren't really about languages, such as symbols like BAGGAGE CLAIM.)

新しい言語がエンコードされると、Unicode は一般的にはその文字のための 連続した未割り当ての符号位置の ブロック を選びます。 今のところ、それらのブロックの符号位置の数は常に 16 で割り切れます。 現在のところ必要ではないブロック中の余地は将来の成長のために 未割り当てのまま残されます。 しかし、後のリリースで利用可能な余地よりも多い符号位置が必要になり、 超えた分を扱うために、元のブロックと連続していない新しいブロックを どこかに割り当てる必要があることがあります。 従って、「ブロック」が適切な組織化方法ではないことが早く明らかになったので、 用字 (Script) 特性が作られました。 (後に改良された用字特性である Script_Extensions も追加されました。) 溢れたブロックにある符号位置も元のものと同じ用字を持ちます。 用字の考え方は自然言語によりよく一致します: Latin 用字があり、Greek 用字があり、などです; 数学記号のような複数の用字で使われる文字のための Common といった、 人工的な用字もいくつかあります。 用字は普通複数のブロックにわたっています。 用字に関するさらなる情報については、"Scripts" in perlunicode を 参照してください。 ブロックに分割されたものはありますが、それは、ほとんど完全に、 予想外のものです--文字がどのように割り当てられるかは不自然な結果です。 (この段落は導入の目的のために単純化しすぎていることに注意してください。 Unicode は実際には言語をエンコードするのではなく、それらの書記体系--用字--を エンコードします; そしてある用字は多くの言語で使われます。 Unicode は BAGGAGE CLAIM のようなシンボルのような、実際には 言語ではないようなものもエンコードします。)

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. 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 の符号位置は、抽象的な数字です。 この抽象的な数字を入出力するために、数字は、何らかの形で エンコード (encode) や シリアライズ (serialise) されなければなりません。 Unicode は、複数の character encoding forms を定義していますが、 その中で、UTF-8 は、たぶん、もっとも有名です。 UTF-8 は、可変長のエンコーディングで、Unicode 文字を 1 から 6 バイト。 他のエンコーディングは、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 v5.6.0, Perl has had the capacity to handle Unicode natively. Perl v5.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 v5.14.0 is the first release where Unicode support is (almost) seamlessly integrable without some gotchas (the exception being some differences in quotemeta, which is fixed starting in Perl 5.16.0). To enable this seamless support, you should use feature 'unicode_strings' (which is automatically selected if you use 5.012 or higher). See feature. (5.14 also fixes a number of bugs and departures from the Unicode standard.)

Perl v5.6.0 から、Perl は、Unicode をネイティブに扱う能力を持っていました。 しかし、重要な Unicode の作業をするためには、Perl v5.8.0 が最初の 推奨できるリリースです。 メンテナンスリリースである 5.6.1 は初期の Unicode 実装の多くの問題を 修正しましたが、例えば、5.6.1 で、Unicode での正規表現はまだ動作しません。 Perl v5.14.0 は、Unicode 対応がいくつかのコツを使うことなく(ほぼ)切れ目なく 統合された最初のリリースです (一部の違いのある例外は quotemeta にあります; これは Perl 5.16.0 から 修正されました)。 この切れ目のない対応を有効にするには、use feature 'unicode_strings' と します(これは use 5.012 またはそれ以上とすると自動的に選択されます)。 feature を参照してください。 (5.14 はまた、多くのバグおよび Unicode 標準からの逸脱を修正しています。)

Before Perl v5.8.0, the use of use utf8 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. Starting with Perl v5.8.0, 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 v5.8.0 以前では、use utf8 の使用は、現在のブロックやファイルの 操作が、Unicode であると明示するのを宣言するために使われました。 このモデルは間違っているか、少なくとも不格好であることがわかりました: 操作に添付するかわりに、"Unicodeness" は、今や、データに持ち込まれています。 Perl v5.8.0 から、唯一残されている、明示的に 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 general 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. Prior to Perl v5.14.0, the upgrade was not completely transparent (see "The "Unicode Bug"" in perlunicode), and for backwards compatibility, full transparency is not gained unless use feature 'unicode_strings' (see feature) or use 5.012 (or higher) is selected.

Perl は、Perl 5.6 より前での 8 ビットネイティブのバイト列の文字列と、 Unicode 文字の文字列の両方をサポートします。 一般的な方針は、Perl は、可能な限り長く 8 ビットバイト列としてデータを 保とうとします; しかし、Unicode 性が避けられなくなった時点で、 データは透過的に Unicode に昇格されます。 Perl v5.14.0 より前では、昇格は完全に透過的ではありませんでした ("The "Unicode Bug"" in perlunicode を参照してください)し、後方互換性のために、 完全な透過性は use feature 'unicode_strings' とするか(feature 参照) use 5.012 (またはそれ以上) が選択されなければ得られませんでした。

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 the same way: 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 likely 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.

Perl 5.8.0 は、EBCDIC プラットフォームでもまた、Unicode をサポートします。 ここでは、各ステップで追加の変換が必要になるので、Unicode サポートは 実装が若干より複雑になります。

Later Perl releases have added code that will not work on EBCDIC platforms, and no one has complained, so the divergence has continued. If you want to run Perl on an EBCDIC platform, send email to perlbug@perl.org

後の Perl リリースには EBCDIC プラットフォームで動作しないコードが追加され、 誰も文句を言わなかったので、相違は続いています。 もし Perl を EBCDIC プラットフォームで実行したいなら、 perlbug@perl.org にメールを送ってください。

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 エンコーディング形式は 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 invoke characters by name in double-quoted strings:

ダブルクォートされた文字列内で、名前で文字を呼び出すこともできます:

    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::string_vianame().

\x{...} と、\N{...} の両方は、コンパイル時の文字列定数です: その中に変数を使うことはできません。 類似のことを実行時にしたいなら、c<chr()> と、charnames::string_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 grapheme clusters to be separate characters, so for example

Perl は書記素クラスタを別々の文字と考えていることに注意して下さい; 従って、例えば

 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 an extended grapheme cluster. (Thus \X in a regular expression would match the entire sequence of both the example characters.)

これは 1 ではなく、2 を表示します。 唯一の例外は、正規表現に拡張書記素クラスタにマッチするために、\X が ある場合です。 (従って正規表現内の \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 the legacy data is assumed to be ISO 8859-1 (or EBCDIC, if applicable).

レガシーデータと 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 currently :utf8 is unsafe for input, because it accepts the data without validating that it is indeed valid UTF-8; you should instead use :encoding(utf-8) (with or without a hyphen).

エンコーディング名のマッチングはルーズです: 大文字小文字は区別されず、 多くのエンコーディングでは、いくつかの別名があります。 :utf8 層は、常に、きっちりとそのように指定される必要があります; このことは、エンコーディング名のルーズなマッチングの対象では ありません。 また、今のところデータが妥当な UTF-8 であるかどうかを検証せずに受け入れるので、 入力に対しては :utf8 は安全ではないことにも注意してください; 代わりに :encoding(utf-8) (ハイフンありかなしかどちらか) を使うべきです。

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 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 は、現在のところ 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 の内容は、2 回 UTF-8 に エンコードされます。 use open 'encoding(utf8)' でバグを避けられ、 もしくは、UTF-8 として入力するために、File を、明示的に開くことです。

NOTE: the :utf8 and :encoding features work only if your Perl has been built with PerlIO, 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 A's should be considered equal, or even A's 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 Report #15, Unicode Normalization Forms and sections on case mapping in the Unicode Standard.

    長く答えるなら、文字の正規化と大文字小文字の問題を考える必要があります: Unicode::Normalize、Unicode テクニカルレポート #15 Unicode Normalization FormsUnicode Standard の大文字小文字マッピングの 章を参照してください。

    As of Perl 5.8.0, the "Full" case-folding of Case Mappings/SpecialCasing is implemented, but bugs remain in qr//i with them, mostly fixed by 5.14, and essentially entirely by 5.18.

    Perl 5.8.0 から、Case Mappings/SpecialCasing の、 「完全な」大文字小文字の畳み込みが実装されていますが、qr//i にバグが 残っています; ほとんどは 5.14 で修正され、5.18 で基本的に全体的に 修正されました。

  • 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 bracketed character classes ( e.g., /[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; for those, if you are using locales (perllocale), use /[[:alpha:]]/; and if not, use the 8-bit-aware property \p{alpha}).

    正規表現の大かっこ文字クラス(/[a-z]/)内と、tr///(y/// としても 知られる)演算子内では、自動的には Unicode 対応にはなりません。 これが意味することは、[A-Za-z] は、自動的に "全てのアルファベット文字"を 意味するようにはなりません(8 ビットの文字であることすらも意味しません; そのためには、ロケール (perllocale) を使っているなら、/[[:alpha:]]/ を 使ってください; そうでなければ、8 ビットを認識する特性 \p{alpha} を 使ってください)。

    All the properties that begin with \p (and its inverse \P) are actually character classes that are Unicode-aware. There are dozens of them, see perluniprops.

    \p (およびその反転である \P) で始まる全ての特性は実際には Unicode に対応した文字クラスです。 これにはたくさんの種類があります; perluniprops を参照してください。

    You can use Unicode code points as the end points of character ranges, and the range will include all Unicode code points that lie between those end points.

    文字の範囲の端の位置として、Unicode の符号位置を使うことができ、幅はこれらの 両端の位置の間の Unicode 符号位置全てを含みます。

  • 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). To get safe conversions from any Unicode string, use "num()" in Unicode::UCD.

    Unicode は、なじみのある、アラビアやインドの数字のような 0 から 9 に加えて、 複数の他の 10 進数--と数字の--文字を、定義します。 Perl は、ASCII の 0 から 9(と、16 進法の ASCII の a から f)以外の 数字の、文字列から数への変換をサポートしません。 任意の Unicode 文字列からの安全な変換を行うには、"num()" in Unicode::UCD を 使ってください。

質問と回答

  • 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. To get full seamless Unicode support, add use feature 'unicode_strings' (or use 5.012 or higher) to your script.

    Unicode データを生成するまで、ほとんど何もする必要はありません。 もっとも重要なものは、Unicode として、入力を得ることです; なので、以前の I/O の議論を見て下さい。 完全に切れ目のない Unicode 対応を使うには、スクリプトに use feature 'unicode_strings' (または use 5.012 またはそれ以上) を 追加してください。

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

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

    You shouldn't have to care. But you may if your Perl is before 5.14.0 or you haven't specified use feature 'unicode_strings' or use 5.012 (or higher) because otherwise the semantics of the code points in the range 128 to 255 are different depending on whether the string they are contained within is in Unicode or not. (See "When Unicode Does Not Happen" in perlunicode.)

    気にする必要はないはずです。 しかし、Perl が 5.14.0 より前か、use feature 'unicode_strings' または use 5.012 (またはそれ以上) が指定されていない場合は必要が あるかもしれません; 範囲 128 から 256 の符号位置の意味論は、文字列が Unicode で保管されているかどうかによって異なるからです。 ("When Unicode Does Not Happen" in 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 (variable-length, potentially multi-byte) UTF-8 encoded code points of the characters. Bytes added to a 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, or 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 でエンコードされた文字の符号位置として解釈されます。 UTF-8 でエンコードされた文字列に追加されたバイトは自動的に 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)
        no bytes;
  • How Do I Find Out What Encoding a File Has?

    ファイルが使っているエンコーディングを見つけるには?

    You might try Encode::Guess, but it has a number of limitations.

    Encode::Guess を試してみることができますが、いくつかの制限があります。

  • 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 は、どのように動きますか?

    If your locale is a UTF-8 locale, starting in Perl v5.20, Perl works well for all categories except LC_COLLATE dealing with sorting and the cmp operator.

    ロケールが UTF-8 ロケールなら、Perl v5.20 から、Perl は、ソートと cmp 演算子での LC_COLLATE の扱い以外の全てのカテゴリでうまく 動作するようになりました。

    For other locales, starting in Perl 5.16, you can specify

    その他のロケールでは、Perl 5.16 から、以下のように指定して、

        use locale ':not_characters';

    to get Perl to work well with them. The catch is that you have to translate from the locale character set to/from Unicode yourself. See "Unicode I/O" above for how to

    Perl がそれらでうまく動作するようにすることができます。 問題点は、ロケール文字集合と Unicode との間の変換を自分でする必要が あるということです。 上述の "Unicode I/O" には

        use open ':locale';

    to accomplish this, but full details are in "Unicode and UTF-8" in perllocale, including gotchas that happen if you don't specify :not_characters.

    を使う方法が記されていますが、:not_characters を指定しなかったときに 起こるコツを含む完全な詳細は "Unicode and UTF-8" in perllocale にあります。

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

更なるリソース

古い 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-2011 Jarkko Hietaniemi <jhi@iki.fi>

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