.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLUNIINTRO 1" .TH PERLUNIINTRO 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide" .SH "NAME" perluniintro \- Perl Unicode introduction .SH "DESCRIPTION" .IX Header "DESCRIPTION" This document gives a general idea of Unicode and how to use Unicode in Perl. .Sh "Unicode" .IX Subsection "Unicode" Unicode is a character set standard which plans to codify all of the writing systems of the world, plus many other symbols. .PP Unicode and \s-1ISO/IEC\s0 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. .PP A Unicode \fIcharacter\fR is an abstract entity. It is not bound to any particular integer width, especially not to the C language \f(CW\*(C`char\*(C'\fR. Unicode is language-neutral and display\-neutral: it does not encode the language of the text and it does not define fonts or other graphical layout details. Unicode operates on characters and on text built from those characters. .PP Unicode defines characters like \f(CW\*(C`LATIN CAPITAL LETTER A\*(C'\fR or \f(CW\*(C`GREEK SMALL LETTER ALPHA\*(C'\fR and unique numbers for the characters, in this case 0x0041 and 0x03B1, respectively. These unique numbers are called \&\fIcode points\fR. .PP The Unicode standard prefers using hexadecimal notation for the code points. If numbers like \f(CW0x0041\fR are unfamiliar to you, take a peek at a later section, \*(L"Hexadecimal Notation\*(R". The Unicode standard uses the notation \f(CW\*(C`U+0041 LATIN CAPITAL LETTER A\*(C'\fR, to give the hexadecimal code point and the normative name of the character. .PP Unicode also defines various \fIproperties\fR for the characters, like \&\*(L"uppercase\*(R" or \*(L"lowercase\*(R", \*(L"decimal digit\*(R", or \*(L"punctuation\*(R"; these properties are independent of the names of the characters. Furthermore, various operations on the characters like uppercasing, lowercasing, and collating (sorting) are defined. .PP A Unicode character consists either of a single code point, or a \&\fIbase character\fR (like \f(CW\*(C`LATIN CAPITAL LETTER A\*(C'\fR), followed by one or more \fImodifiers\fR (like \f(CW\*(C`COMBINING ACUTE ACCENT\*(C'\fR). This sequence of base character and modifiers is called a \fIcombining character sequence\fR. .PP Whether to call these combining character sequences \*(L"characters\*(R" 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 \*(L"character\*(R". The whole sequence could be seen as one \*(L"character\*(R", however, from the user's point of view, since that's probably what it looks like in the context of the user's language. .PP With this \*(L"whole sequence\*(R" view of characters, the total number of characters is open\-ended. But in the programmer's \*(L"one unit is one character\*(R" point of view, the concept of \*(L"characters\*(R" is more deterministic. In this document, we take that second point of view: one \*(L"character\*(R" is one Unicode code point, be it a base character or a combining character. .PP For some combinations, there are \fIprecomposed\fR characters. \&\f(CW\*(C`LATIN CAPITAL LETTER A WITH ACUTE\*(C'\fR, 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 \s-1ISO\s0 8859). In the general case, the composing method is more extensible. To support conversion between different compositions of the characters, various \fInormalization forms\fR to standardize representations are also defined. .PP Because of backward compatibility with legacy encodings, the \*(L"a unique number for every character\*(R" idea breaks down a bit: instead, there is \&\*(L"at least one number for every character\*(R". 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. .PP A common myth about Unicode is that it would be \*(L"16\-bit\*(R", that is, Unicode is only represented as \f(CW0x10000\fR (or 65536) characters from \&\f(CW0x0000\fR to \f(CW0xFFFF\fR. \fBThis is untrue.\fR Since Unicode 2.0, Unicode has been defined all the way up to 21 bits (\f(CW0x10FFFF\fR), and since Unicode 3.1, characters have been defined beyond \f(CW0xFFFF\fR. The first \&\f(CW0x10000\fR characters are called the \fIPlane 0\fR, or the \fIBasic Multilingual Plane\fR (\s-1BMP\s0). With Unicode 3.1, 17 planes in all are defined\*(--but nowhere near full of defined characters, yet. .PP 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. \fBThis is also untrue.\fR 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 \fIscripts\fR, which is more useful: there is \f(CW\*(C`Latin\*(C'\fR script, \f(CW\*(C`Greek\*(C'\fR script, and so on. Scripts usually span varied parts of several blocks. For further information see Unicode::UCD. .PP The Unicode code points are just abstract numbers. To input and output these abstract numbers, the numbers must be \fIencoded\fR somehow. Unicode defines several \fIcharacter encoding forms\fR, of which \fI\s-1UTF\-8\s0\fR is perhaps the most popular. \s-1UTF\-8\s0 is a variable length encoding that encodes Unicode characters as 1 to 6 bytes (only 4 with the currently defined characters). Other encodings include \s-1UTF\-16\s0 and \s-1UTF\-32\s0 and their big\- and little-endian variants (\s-1UTF\-8\s0 is byte-order independent) The \s-1ISO/IEC\s0 10646 defines the \s-1UCS\-2\s0 and \s-1UCS\-4\s0 encoding forms. .PP For more information about encodings\*(--for instance, to learn what \&\fIsurrogates\fR and \fIbyte order marks\fR (BOMs) are\*(--see perlunicode. .Sh "Perl's Unicode Support" .IX Subsection "Perl's Unicode Support" 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. .PP \&\fBStarting from Perl 5.8.0, the use of \f(CB\*(C`use utf8\*(C'\fB is no longer necessary.\fR In earlier releases the \f(CW\*(C`utf8\*(C'\fR 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 \*(L"Unicodeness\*(R" is now carried with the data, instead of being attached to the operations. Only one case remains where an explicit \f(CW\*(C`use utf8\*(C'\fR is needed: if your Perl script itself is encoded in \s-1UTF\-8\s0, you can use \&\s-1UTF\-8\s0 in your identifier names, and in string and regular expression literals, by saying \f(CW\*(C`use utf8\*(C'\fR. This is not the default because scripts with legacy 8\-bit data in them would break. See utf8. .Sh "Perl's Unicode Model" .IX Subsection "Perl's Unicode Model" 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. .PP Internally, Perl currently uses either whatever the native eight-bit character set of the platform (for example Latin\-1) is, defaulting to \&\s-1UTF\-8\s0, to encode Unicode strings. Specifically, if all code points in the string are \f(CW0xFF\fR or less, Perl uses the native eight-bit character set. Otherwise, it uses \s-1UTF\-8\s0. .PP 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 \*(L"default\*(R" encoding. In such a case, the raw bytes used internally (the native character set or \s-1UTF\-8\s0, as appropriate for each string) will be used, and a \*(L"Wide character\*(R" warning will be issued if those strings contain a character beyond 0x00FF. .PP For example, .PP .Vb 1 \& perl -e 'print "\ex{DF}\en", "\ex{0100}\ex{DF}\en"' .Ve .PP produces a fairly useless mixture of native bytes and \s-1UTF\-8\s0, as well as a warning: .PP .Vb 1 \& Wide character in print at ... .Ve .PP To output \s-1UTF\-8\s0, use the \f(CW\*(C`:utf8\*(C'\fR output layer. Prepending .PP .Vb 1 \& binmode(STDOUT, ":utf8"); .Ve .PP to this sample program ensures that the output is completely \s-1UTF\-8\s0, and removes the program's warning. .PP If your locale environment variables (\f(CW\*(C`LANGUAGE\*(C'\fR, \f(CW\*(C`LC_ALL\*(C'\fR, \&\f(CW\*(C`LC_CTYPE\*(C'\fR, \f(CW\*(C`LANG\*(C'\fR) contain the strings '\s-1UTF\-8\s0' or '\s-1UTF8\s0', regardless of case, then the default encoding of your \s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 and of \fBany subsequent file open\fR, is \s-1UTF\-8\s0. Note that this means that Perl expects other software to work, too: if Perl has been led to believe that \s-1STDIN\s0 should be \s-1UTF\-8\s0, but then \s-1STDIN\s0 coming in from another command is not \s-1UTF\-8\s0, Perl will complain about the malformed \s-1UTF\-8\s0. .PP 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 \*(L"perl \-V\*(R" and looking for \&\f(CW\*(C`useperlio=define\*(C'\fR. .Sh "Unicode and \s-1EBCDIC\s0" .IX Subsection "Unicode and EBCDIC" Perl 5.8.0 also supports Unicode on \s-1EBCDIC\s0 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. .PP In any case, the Unicode support on \s-1EBCDIC\s0 platforms is better than in the 5.6 series, which didn't work much at all for \s-1EBCDIC\s0 platform. On \s-1EBCDIC\s0 platforms, the internal Unicode encoding form is UTF-EBCDIC instead of \s-1UTF\-8\s0. The difference is that as \s-1UTF\-8\s0 is \*(L"ASCII\-safe\*(R" in that \s-1ASCII\s0 characters encode to \s-1UTF\-8\s0 as\-is, while UTF-EBCDIC is \&\*(L"EBCDIC\-safe\*(R". .Sh "Creating Unicode" .IX Subsection "Creating Unicode" To create Unicode characters in literals for code points above \f(CW0xFF\fR, use the \f(CW\*(C`\ex{...}\*(C'\fR notation in double-quoted strings: .PP .Vb 1 \& my $smiley = "\ex{263a}"; .Ve .PP Similarly, it can be used in regular expression literals .PP .Vb 1 \& $smiley =~ /\ex{263a}/; .Ve .PP At run-time you can use \f(CW\*(C`chr()\*(C'\fR: .PP .Vb 1 \& my $hebrew_alef = chr(0x05d0); .Ve .PP See \*(L"Further Resources\*(R" for how to find all these numeric codes. .PP Naturally, \f(CW\*(C`ord()\*(C'\fR will do the reverse: it turns a character into a code point. .PP Note that \f(CW\*(C`\ex..\*(C'\fR (no \f(CW\*(C`{}\*(C'\fR and only two hexadecimal digits), \f(CW\*(C`\ex{...}\*(C'\fR, and \f(CW\*(C`chr(...)\*(C'\fR for arguments less than \f(CW0x100\fR (decimal 256) generate an eight-bit character for backward compatibility with older Perls. For arguments of \f(CW0x100\fR or more, Unicode characters are always produced. If you want to force the production of Unicode characters regardless of the numeric value, use \f(CW\*(C`pack("U", ...)\*(C'\fR instead of \f(CW\*(C`\ex..\*(C'\fR, \f(CW\*(C`\ex{...}\*(C'\fR, or \f(CW\*(C`chr()\*(C'\fR. .PP You can also use the \f(CW\*(C`charnames\*(C'\fR pragma to invoke characters by name in double-quoted strings: .PP .Vb 2 \& use charnames ':full'; \& my $arabic_alef = "\eN{ARABIC LETTER ALEF}"; .Ve .PP And, as mentioned above, you can also \f(CW\*(C`pack()\*(C'\fR numbers into Unicode characters: .PP .Vb 1 \& my $georgian_an = pack("U", 0x10a0); .Ve .PP Note that both \f(CW\*(C`\ex{...}\*(C'\fR and \f(CW\*(C`\eN{...}\*(C'\fR are compile-time string constants: you cannot use variables in them. if you want similar run-time functionality, use \f(CW\*(C`chr()\*(C'\fR and \f(CW\*(C`charnames::vianame()\*(C'\fR. .PP Also note that if all the code points for pack \*(L"U\*(R" are below 0x100, bytes will be generated, just like if you were using \f(CW\*(C`chr()\*(C'\fR. .PP .Vb 1 \& my $bytes = pack("U*", 0x80, 0xFF); .Ve .PP If you want to force the result to Unicode characters, use the special \&\f(CW"U0"\fR prefix. It consumes no arguments but forces the result to be in Unicode characters, instead of bytes. .PP .Vb 1 \& my $chars = pack("U0U*", 0x80, 0xFF); .Ve .Sh "Handling Unicode" .IX Subsection "Handling Unicode" Handling Unicode is for the most part transparent: just use the strings as usual. Functions like \f(CW\*(C`index()\*(C'\fR, \f(CW\*(C`length()\*(C'\fR, and \&\f(CW\*(C`substr()\*(C'\fR will work on the Unicode characters; regular expressions will work on the Unicode characters (see perlunicode and perlretut). .PP Note that Perl considers combining character sequences to be characters, so for example .PP .Vb 2 \& use charnames ':full'; \& print length("\eN{LATIN CAPITAL LETTER A}\eN{COMBINING ACUTE ACCENT}"), "\en"; .Ve .PP will print 2, not 1. The only exception is that regular expressions have \f(CW\*(C`\eX\*(C'\fR for matching a combining character sequence. .PP Life is not quite so transparent, however, when working with legacy encodings, I/O, and certain special cases: .Sh "Legacy Encodings" .IX Subsection "Legacy Encodings" When you combine legacy data and Unicode the legacy data needs to be upgraded to Unicode. Normally \s-1ISO\s0 8859\-1 (or \s-1EBCDIC\s0, if applicable) is assumed. You can override this assumption by using the \f(CW\*(C`encoding\*(C'\fR pragma, for example .PP .Vb 1 \& use encoding 'latin2'; # ISO 8859-2 .Ve .PP in which case literals (string or regular expressions), \f(CW\*(C`chr()\*(C'\fR, and \f(CW\*(C`ord()\*(C'\fR in your whole script are assumed to produce Unicode characters from \s-1ISO\s0 8859\-2 code points. Note that the matching for encoding names is forgiving: instead of \f(CW\*(C`latin2\*(C'\fR you could have said \f(CW\*(C`Latin 2\*(C'\fR, or \f(CW\*(C`iso8859\-2\*(C'\fR, or other variations. With just .PP .Vb 1 \& use encoding; .Ve .PP the environment variable \f(CW\*(C`PERL_ENCODING\*(C'\fR will be consulted. If that variable isn't set, the encoding pragma will fail. .PP The \f(CW\*(C`Encode\*(C'\fR module knows about many encodings and has interfaces for doing conversions between those encodings: .PP .Vb 2 \& use Encode 'from_to'; \& from_to($data, "iso-8859-3", "utf-8"); # from legacy to utf-8 .Ve .Sh "Unicode I/O" .IX Subsection "Unicode I/O" Normally, writing out Unicode data .PP .Vb 1 \& print FH $some_string_with_unicode, "\en"; .Ve .PP 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 \f(CW0x100\fR 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: .PP .Vb 1 \& open FH, ">:utf8", "file"; .Ve .PP .Vb 3 \& open FH, ">:encoding(ucs2)", "file"; \& open FH, ">:encoding(UTF-8)", "file"; \& open FH, ">:encoding(shift_jis)", "file"; .Ve .PP and on already open streams, use \f(CW\*(C`binmode()\*(C'\fR: .PP .Vb 1 \& binmode(STDOUT, ":utf8"); .Ve .PP .Vb 3 \& binmode(STDOUT, ":encoding(ucs2)"); \& binmode(STDOUT, ":encoding(UTF-8)"); \& binmode(STDOUT, ":encoding(shift_jis)"); .Ve .PP The matching of encoding names is loose: case does not matter, and many encodings have several aliases. Note that the \f(CW\*(C`:utf8\*(C'\fR layer must always be specified exactly like that; it is \fInot\fR subject to the loose matching of encoding names. .PP See PerlIO for the \f(CW\*(C`:utf8\*(C'\fR layer, PerlIO::encoding and Encode::PerlIO for the \f(CW\*(C`:encoding()\*(C'\fR layer, and Encode::Supported for many encodings supported by the \f(CW\*(C`Encode\*(C'\fR module. .PP 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 .PP .Vb 2 \& open(my $fh,'<:utf8', 'anything'); \& my $line_of_unicode = <$fh>; .Ve .PP .Vb 2 \& open(my $fh,'<:encoding(Big5)', 'anything'); \& my $line_of_unicode = <$fh>; .Ve .PP The I/O layers can also be specified more flexibly with the \f(CW\*(C`open\*(C'\fR pragma. See open, or look at the following example. .PP .Vb 7 \& use open ':utf8'; # input and output default layer will be UTF-8 \& open X, ">file"; \& print X chr(0x100), "\en"; \& close X; \& open Y, "); # this should print 0x100 \& close Y; .Ve .PP With the \f(CW\*(C`open\*(C'\fR pragma you can use the \f(CW\*(C`:locale\*(C'\fR layer .PP .Vb 9 \& $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, "), "\en"; # this should print 0xc1 \& close I; .Ve .PP or you can also use the \f(CW':encoding(...)'\fR layer .PP .Vb 2 \& open(my $epic,'<:encoding(iso-8859-7)','iliad.greek'); \& my $line_of_unicode = <$epic>; .Ve .PP 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. .PP The open pragma affects all the \f(CW\*(C`open()\*(C'\fR calls after the pragma by setting default layers. If you want to affect only certain streams, use explicit layers directly in the \f(CW\*(C`open()\*(C'\fR call. .PP You can switch encodings on an already opened stream by using \&\f(CW\*(C`binmode()\*(C'\fR; see \*(L"binmode\*(R" in perlfunc. .PP The \f(CW\*(C`:locale\*(C'\fR does not currently (as of Perl 5.8.0) work with \&\f(CW\*(C`open()\*(C'\fR and \f(CW\*(C`binmode()\*(C'\fR, only with the \f(CW\*(C`open\*(C'\fR pragma. The \&\f(CW\*(C`:utf8\*(C'\fR and \f(CW\*(C`:encoding(...)\*(C'\fR methods do work with all of \f(CW\*(C`open()\*(C'\fR, \&\f(CW\*(C`binmode()\*(C'\fR, and the \f(CW\*(C`open\*(C'\fR pragma. .PP 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 \*(L"text.jis\*(R" (encoded as \s-1ISO\-2022\-JP\s0, aka \s-1JIS\s0) to the file \*(L"text.utf8\*(R", encoded as \s-1UTF\-8:\s0 .PP .Vb 3 \& open(my $nihongo, '<:encoding(iso2022-jp)', 'text.jis'); \& open(my $unicode, '>:utf8', 'text.utf8'); \& while (<$nihongo>) { print $unicode } .Ve .PP The naming of encodings, both by the \f(CW\*(C`open()\*(C'\fR and by the \f(CW\*(C`open\*(C'\fR pragma, is similar to the \f(CW\*(C`encoding\*(C'\fR pragma in that it allows for flexible names: \f(CW\*(C`koi8\-r\*(C'\fR and \f(CW\*(C`KOI8R\*(C'\fR will both be understood. .PP Common encodings recognized by \s-1ISO\s0, \s-1MIME\s0, \s-1IANA\s0, and various other standardisation organisations are recognised; for a more detailed list see Encode::Supported. .PP \&\f(CW\*(C`read()\*(C'\fR reads characters and returns the number of characters. \&\f(CW\*(C`seek()\*(C'\fR and \f(CW\*(C`tell()\*(C'\fR operate on byte counts, as do \f(CW\*(C`sysread()\*(C'\fR and \f(CW\*(C`sysseek()\*(C'\fR. .PP 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: .PP .Vb 8 \& # BAD CODE WARNING \& open F, "file"; \& local $/; ## read in the whole file of 8-bit characters \& $t = ; \& close F; \& open F, ">:utf8", "file"; \& print F $t; ## convert to UTF-8 on output \& close F; .Ve .PP If you run this code twice, the contents of the \fIfile\fR will be twice \&\s-1UTF\-8\s0 encoded. A \f(CW\*(C`use open ':utf8'\*(C'\fR would have avoided the bug, or explicitly opening also the \fIfile\fR for input as \s-1UTF\-8\s0. .PP \&\fB\s-1NOTE\s0\fR: the \f(CW\*(C`:utf8\*(C'\fR and \f(CW\*(C`:encoding\*(C'\fR features work only if your Perl has been built with the new PerlIO feature. .Sh "Displaying Unicode As Text" .IX Subsection "Displaying Unicode As Text" Sometimes you might want to display Perl scalars containing Unicode as simple \s-1ASCII\s0 (or \s-1EBCDIC\s0) text. The following subroutine converts its argument so that Unicode characters with code points greater than 255 are displayed as \f(CW\*(C`\ex{...}\*(C'\fR, control characters (like \f(CW\*(C`\en\*(C'\fR) are displayed as \f(CW\*(C`\ex..\*(C'\fR, and the rest of the characters as themselves: .PP .Vb 9 \& sub nice_string { \& join("", \& map { $_ > 255 ? # if wide character... \& sprintf("\e\ex{%04X}", $_) : # \ex{...} \& chr($_) =~ /[[:cntrl:]]/ ? # else if control character ... \& sprintf("\e\ex%02X", $_) : # \ex.. \& chr($_) # else as themselves \& } unpack("U*", $_[0])); # unpack Unicode characters \& } .Ve .PP For example, .PP .Vb 1 \& nice_string("foo\ex{100}bar\en") .Ve .PP returns: .PP .Vb 1 \& "foo\ex{0100}bar\ex0A" .Ve .Sh "Special Cases" .IX Subsection "Special Cases" .IP "\(bu" 4 Bit Complement Operator ~ And \fIvec()\fR .Sp The bit complement operator \f(CW\*(C`~\*(C'\fR 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 \f(CW\*(C`vec()\*(C'\fR: 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. .IP "\(bu" 4 Peeking At Perl's Internal Encoding .Sp 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. .Sp One way of peeking inside the internal encoding of Unicode characters is to use \f(CW\*(C`unpack("C*", ...\*(C'\fR to get the bytes or \f(CW\*(C`unpack("H*", ...)\*(C'\fR to display the bytes: .Sp .Vb 2 \& # this prints c4 80 for the UTF-8 bytes 0xc4 0x80 \& print join(" ", unpack("H*", pack("U", 0x100))), "\en"; .Ve .Sp Yet another way would be to use the Devel::Peek module: .Sp .Vb 1 \& perl -MDevel::Peek -e 'Dump(chr(0x100))' .Ve .Sp That shows the \s-1UTF8\s0 flag in \s-1FLAGS\s0 and both the \s-1UTF\-8\s0 bytes and Unicode characters in \f(CW\*(C`PV\*(C'\fR. See also later in this document the discussion about the \f(CW\*(C`is_utf8\*(C'\fR function of the \f(CW\*(C`Encode\*(C'\fR module. .Sh "Advanced Topics" .IX Subsection "Advanced Topics" .IP "\(bu" 4 String Equivalence .Sp The question of string equivalence turns somewhat complicated in Unicode: what do you mean by \*(L"equal\*(R"? .Sp (Is \f(CW\*(C`LATIN CAPITAL LETTER A WITH ACUTE\*(C'\fR equal to \&\f(CW\*(C`LATIN CAPITAL LETTER A\*(C'\fR?) .Sp The short answer is that by default Perl compares equivalence (\f(CW\*(C`eq\*(C'\fR, \&\f(CW\*(C`ne\*(C'\fR) based only on code points of the characters. In the above case, the answer is no (because 0x00C1 != 0x0041). But sometimes, any \&\s-1CAPITAL\s0 \s-1LETTER\s0 As should be considered equal, or even As of any case. .Sp The long answer is that you need to consider character normalization and casing issues: see Unicode::Normalize, Unicode Technical Reports #15 and #21, \fIUnicode Normalization Forms\fR and \fICase Mappings\fR, http://www.unicode.org/unicode/reports/tr15/ and http://www.unicode.org/unicode/reports/tr21/ .Sp As of Perl 5.8.0, the \*(L"Full\*(R" case-folding of \fICase Mappings/SpecialCasing\fR is implemented. .IP "\(bu" 4 String Collation .Sp People like to see their strings nicely sorted\*(--or as Unicode parlance goes, collated. But again, what do you mean by collate? .Sp (Does \f(CW\*(C`LATIN CAPITAL LETTER A WITH ACUTE\*(C'\fR come before or after \&\f(CW\*(C`LATIN CAPITAL LETTER A WITH GRAVE\*(C'\fR?) .Sp The short answer is that by default, Perl compares strings (\f(CW\*(C`lt\*(C'\fR, \&\f(CW\*(C`le\*(C'\fR, \f(CW\*(C`cmp\*(C'\fR, \f(CW\*(C`ge\*(C'\fR, \f(CW\*(C`gt\*(C'\fR) based only on the code points of the characters. In the above case, the answer is \*(L"after\*(R", since \&\f(CW0x00C1\fR > \f(CW0x00C0\fR. .Sp The long answer is that \*(L"it depends\*(R", and a good answer cannot be given without knowing (at the very least) the language context. See Unicode::Collate, and \fIUnicode Collation Algorithm\fR http://www.unicode.org/unicode/reports/tr10/ .Sh "Miscellaneous" .IX Subsection "Miscellaneous" .IP "\(bu" 4 Character Ranges and Classes .Sp Character ranges in regular expression character classes (\f(CW\*(C`/[a\-z]/\*(C'\fR) and in the \f(CW\*(C`tr///\*(C'\fR (also known as \f(CW\*(C`y///\*(C'\fR) operator are not magically Unicode\-aware. What this means that \f(CW\*(C`[A\-Za\-z]\*(C'\fR will not magically start to mean \*(L"all alphabetic letters\*(R"; not that it does mean that even for 8\-bit characters, you should be using \f(CW\*(C`/[[:alpha:]]/\*(C'\fR in that case. .Sp For specifying character classes like that in regular expressions, you can use the various Unicode properties\*(--\f(CW\*(C`\epL\*(C'\fR, or perhaps \&\f(CW\*(C`\ep{Alphabetic}\*(C'\fR, 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. .IP "\(bu" 4 String-To-Number Conversions .Sp 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 \s-1ASCII\s0 0 to 9 (and \s-1ASCII\s0 a to f for hexadecimal). .Sh "Questions With Answers" .IX Subsection "Questions With Answers" .IP "\(bu" 4 Will My Old Scripts Break? .Sp 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 \f(CW\*(C`chr()\*(C'\fR where supplying an argument more than 255 produced a character modulo 255. \f(CW\*(C`chr(300)\*(C'\fR, for example, was equal to \f(CW\*(C`chr(45)\*(C'\fR or \*(L"\-\*(R" (in \s-1ASCII\s0), now it is \s-1LATIN\s0 \s-1CAPITAL\s0 \s-1LETTER\s0 I \s-1WITH\s0 \&\s-1BREVE\s0. .IP "\(bu" 4 How Do I Make My Scripts Work With Unicode? .Sp 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. .IP "\(bu" 4 How Do I Know Whether My String Is In Unicode? .Sp You shouldn't care. No, you really shouldn't. No, really. If you have to care\*(--beyond the cases described above\*(--it means that we didn't get the transparency of Unicode quite right. .Sp Okay, if you insist: .Sp .Vb 2 \& use Encode 'is_utf8'; \& print is_utf8($string) ? 1 : 0, "\en"; .Ve .Sp But note that this doesn't mean that any of the characters in the string are necessary \s-1UTF\-8\s0 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 \f(CW\*(C`is_utf8()\*(C'\fR does is to return the value of the internal \*(L"utf8ness\*(R" flag attached to the \&\f(CW$string\fR. 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) \s-1UTF\-8\s0 encoded code points of the characters. Bytes added to an \s-1UTF\-8\s0 encoded string are automatically upgraded to \s-1UTF\-8\s0. If mixed non\-UTF8 and \s-1UTF\-8\s0 scalars are merged (double\-quoted interpolation, explicit concatenation, and printf/sprintf parameter substitution), the result will be \s-1UTF\-8\s0 encoded as if copies of the byte strings were upgraded to \s-1UTF\-8:\s0 for example, .Sp .Vb 3 \& $a = "ab\ex80c"; \& $b = "\ex{100}"; \& print "$a = $b\en"; .Ve .Sp the output string will be UTF\-8\-encoded \f(CW\*(C`ab\ex80c\ex{100}\en\*(C'\fR, but note that \f(CW$a\fR will stay byte\-encoded. .Sp Sometimes you might really need to know the byte length of a string instead of the character length. For that use either the \&\f(CW\*(C`Encode::encode_utf8()\*(C'\fR function or the \f(CW\*(C`bytes\*(C'\fR pragma and its only defined function \f(CW\*(C`length()\*(C'\fR: .Sp .Vb 7 \& my $unicode = chr(0x100); \& print length($unicode), "\en"; # will print 1 \& require Encode; \& print length(Encode::encode_utf8($unicode)), "\en"; # will print 2 \& use bytes; \& print length($unicode), "\en"; # will also print 2 \& # (the 0xC4 0x80 of the UTF-8) .Ve .IP "\(bu" 4 How Do I Detect Data That's Not Valid In a Particular Encoding? .Sp Use the \f(CW\*(C`Encode\*(C'\fR package to try converting it. For example, .Sp .Vb 6 \& use Encode 'encode_utf8'; \& if (encode_utf8($string_of_bytes_that_I_think_is_utf8)) { \& # valid \& } else { \& # invalid \& } .Ve .Sp For \s-1UTF\-8\s0 only, you can use: .Sp .Vb 2 \& use warnings; \& @chars = unpack("U0U*", $string_of_bytes_that_I_think_is_utf8); .Ve .Sp If invalid, a \f(CW\*(C`Malformed UTF\-8 character (byte 0x##) in unpack\*(C'\fR warning is produced. The \*(L"U0\*(R" means \*(L"expect strictly \s-1UTF\-8\s0 encoded Unicode\*(R". Without that the \f(CW\*(C`unpack("U*", ...)\*(C'\fR would accept also data like \f(CW\*(C`chr(0xFF\*(C'\fR), similarly to the \f(CW\*(C`pack\*(C'\fR as we saw earlier. .IP "\(bu" 4 How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa? .Sp This probably isn't as useful as you might think. Normally, you shouldn't need to. .Sp In one sense, what you are asking doesn't make much sense: encodings are for characters, and binary data are not \*(L"characters\*(R", so converting \&\*(L"data\*(R" 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? .Sp If you have a raw sequence of bytes that you know should be interpreted via a particular encoding, you can use \f(CW\*(C`Encode\*(C'\fR: .Sp .Vb 2 \& use Encode 'from_to'; \& from_to($data, "iso-8859-1", "utf-8"); # from latin-1 to utf-8 .Ve .Sp The call to \f(CW\*(C`from_to()\*(C'\fR changes the bytes in \f(CW$data\fR, 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 \f(CW$data\fR contains just a bunch of 8\-bit bytes. As far as Perl is concerned, the encoding of the string remains as \*(L"system\-native 8\-bit bytes\*(R". .Sp You might relate this to a fictional 'Translate' module: .Sp .Vb 4 \& use Translate; \& my $phrase = "Yes"; \& Translate::from_to($phrase, 'english', 'deutsch'); \& ## phrase now contains "Ja" .Ve .Sp 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. .Sp Back to converting data. If you have (or want) data in your system's native 8\-bit encoding (e.g. Latin\-1, \s-1EBCDIC\s0, etc.), you can use pack/unpack to convert to/from Unicode. .Sp .Vb 2 \& $native_string = pack("C*", unpack("U*", $Unicode_string)); \& $Unicode_string = pack("U*", unpack("C*", $native_string)); .Ve .Sp If you have a sequence of bytes you \fBknow\fR is valid \s-1UTF\-8\s0, but Perl doesn't know it yet, you can make Perl a believer, too: .Sp .Vb 2 \& use Encode 'decode_utf8'; \& $Unicode = decode_utf8($bytes); .Ve .Sp You can convert well-formed \s-1UTF\-8\s0 to a sequence of bytes, but if you just want to convert random binary data into \s-1UTF\-8\s0, you can't. \&\fBAny random collection of bytes isn't well-formed \s-1UTF\-8\s0\fR. You can use \f(CW\*(C`unpack("C*", $string)\*(C'\fR for the former, and you can create well-formed Unicode data by \f(CW\*(C`pack("U*", 0xff, ...)\*(C'\fR. .IP "\(bu" 4 How Do I Display Unicode? How Do I Input Unicode? .Sp See http://www.alanwood.net/unicode/ and http://www.cl.cam.ac.uk/~mgk25/unicode.html .IP "\(bu" 4 How Does Unicode Work With Traditional Locales? .Sp In Perl, not very well. Avoid using locales through the \f(CW\*(C`locale\*(C'\fR pragma. Use only one or the other. .Sh "Hexadecimal Notation" .IX Subsection "Hexadecimal Notation" 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 \f(CW\*(C`U+HHHH\*(C'\fR notation uses hexadecimal, for example. .PP The \f(CW\*(C`0x\*(C'\fR prefix means a hexadecimal number, the digits are 0\-9 \fIand\fR a\-f (or A\-F, case doesn't matter). Each hexadecimal digit represents four bits, or half a byte. \f(CW\*(C`print 0x..., "\en"\*(C'\fR will show a hexadecimal number in decimal, and \f(CW\*(C`printf "%x\en", $decimal\*(C'\fR will show a decimal number in hexadecimal. If you have just the \&\*(L"hex digits\*(R" of a hexadecimal number, you can use the \f(CW\*(C`hex()\*(C'\fR function. .PP .Vb 6 \& print 0x0009, "\en"; # 9 \& print 0x000a, "\en"; # 10 \& print 0x000f, "\en"; # 15 \& print 0x0010, "\en"; # 16 \& print 0x0011, "\en"; # 17 \& print 0x0100, "\en"; # 256 .Ve .PP .Vb 1 \& print 0x0041, "\en"; # 65 .Ve .PP .Vb 2 \& printf "%x\en", 65; # 41 \& printf "%#x\en", 65; # 0x41 .Ve .PP .Vb 1 \& print hex("41"), "\en"; # 65 .Ve .Sh "Further Resources" .IX Subsection "Further Resources" .IP "\(bu" 4 Unicode Consortium .Sp .Vb 1 \& http://www.unicode.org/ .Ve .IP "\(bu" 4 Unicode \s-1FAQ\s0 .Sp .Vb 1 \& http://www.unicode.org/unicode/faq/ .Ve .IP "\(bu" 4 Unicode Glossary .Sp .Vb 1 \& http://www.unicode.org/glossary/ .Ve .IP "\(bu" 4 Unicode Useful Resources .Sp .Vb 1 \& http://www.unicode.org/unicode/onlinedat/resources.html .Ve .IP "\(bu" 4 Unicode and Multilingual Support in \s-1HTML\s0, Fonts, Web Browsers and Other Applications .Sp .Vb 1 \& http://www.alanwood.net/unicode/ .Ve .IP "\(bu" 4 \&\s-1UTF\-8\s0 and Unicode \s-1FAQ\s0 for Unix/Linux .Sp .Vb 1 \& http://www.cl.cam.ac.uk/~mgk25/unicode.html .Ve .IP "\(bu" 4 Legacy Character Sets .Sp .Vb 2 \& http://www.czyborra.com/ \& http://www.eki.ee/letter/ .Ve .IP "\(bu" 4 The Unicode support files live within the Perl installation in the directory .Sp .Vb 1 \& $Config{installprivlib}/unicore .Ve .Sp in Perl 5.8.0 or newer, and .Sp .Vb 1 \& $Config{installprivlib}/unicode .Ve .Sp in the Perl 5.6 series. (The renaming to \fIlib/unicore\fR was done to avoid naming conflicts with lib/Unicode in case-insensitive filesystems.) The main Unicode data file is \fIUnicodeData.txt\fR (or \fIUnicode.301\fR in Perl 5.6.1.) You can find the \f(CW$Config{installprivlib}\fR by .Sp .Vb 1 \& perl "-V:installprivlib" .Ve .Sp You can explore various information from the Unicode data files using the \f(CW\*(C`Unicode::UCD\*(C'\fR module. .SH "UNICODE IN OLDER PERLS" .IX Header "UNICODE IN OLDER PERLS" If you cannot upgrade your Perl to 5.8.0 or later, you can still do some Unicode processing by using the modules \f(CW\*(C`Unicode::String\*(C'\fR, \&\f(CW\*(C`Unicode::Map8\*(C'\fR, and \f(CW\*(C`Unicode::Map\*(C'\fR, available from \s-1CPAN\s0. If you have the \s-1GNU\s0 recode installed, you can also use the Perl front-end \f(CW\*(C`Convert::Recode\*(C'\fR for character conversions. .PP The following are fast conversions from \s-1ISO\s0 8859\-1 (Latin\-1) bytes to \s-1UTF\-8\s0 bytes, the code works even with older Perl 5 versions. .PP .Vb 2 \& # ISO 8859-1 to UTF-8 \& s/([\ex80-\exFF])/chr(0xC0|ord($1)>>6).chr(0x80|ord($1)&0x3F)/eg; .Ve .PP .Vb 2 \& # UTF-8 to ISO 8859-1 \& s/([\exC2\exC3])([\ex80-\exBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg; .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" perlunicode, Encode, encoding, open, utf8, bytes, perlretut, Unicode::Collate, Unicode::Normalize, Unicode::UCD .SH "ACKNOWLEDGMENTS" .IX Header "ACKNOWLEDGMENTS" 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. .SH "AUTHOR, COPYRIGHT, AND LICENSE" .IX Header "AUTHOR, COPYRIGHT, AND LICENSE" Copyright 2001\-2002 Jarkko Hietaniemi .PP This document may be distributed under the same terms as Perl itself.