Commit | Line | Data |
ba62762e |
1 | =head1 NAME |
2 | |
07fcf8ff |
3 | perluniintro - Perl Unicode introduction |
ba62762e |
4 | |
5 | =head1 DESCRIPTION |
6 | |
7 | This document gives a general idea of Unicode and how to use Unicode |
8 | in Perl. |
9 | |
10 | =head2 Unicode |
11 | |
12 | Unicode is a character set standard with plans to cover all of the |
13 | writing systems of the world, plus many other symbols. |
14 | |
15 | Unicode and ISO/IEC 10646 are coordinated standards that provide code |
16 | points for the characters in almost all modern character set standards, |
17 | covering more than 30 writing systems and hundreds of languages, |
18 | including all commercially important modern languages. All characters |
19 | in the largest Chinese, Japanese, and Korean dictionaries are also |
20 | encoded. The standards will eventually cover almost all characters in |
21 | more than 250 writing systems and thousands of languages. |
22 | |
23 | A Unicode I<character> is an abstract entity. It is not bound to any |
24 | particular integer width, and especially not to the C language C<char>. |
25 | Unicode is language neutral and display neutral: it doesn't encode the |
26 | language of the text, and it doesn't define fonts or other graphical |
27 | layout details. Unicode operates on characters and on text built from |
28 | those characters. |
29 | |
30 | Unicode defines characters like C<LATIN CAPITAL LETTER A> or C<GREEK |
31 | SMALL LETTER ALPHA>, and then unique numbers for those, hexadecimal |
32 | 0x0041 or 0x03B1 for those particular characters. Such unique |
33 | numbers are called I<code points>. |
34 | |
35 | The Unicode standard prefers using hexadecimal notation for the code |
36 | points. (In case this notation, numbers like 0x0041, is unfamiliar to |
37 | you, take a peek at a later section, L</"Hexadecimal Notation">.) |
38 | The Unicode standard uses the notation C<U+0041 LATIN CAPITAL LETTER A>, |
39 | which gives the hexadecimal code point, and the normative name of |
40 | the character. |
41 | |
42 | Unicode also defines various I<properties> for the characters, like |
43 | "uppercase" or "lowercase", "decimal digit", or "punctuation": |
44 | these properties are independent of the names of the characters. |
45 | Furthermore, various operations on the characters like uppercasing, |
46 | lowercasing, and collating (sorting), are defined. |
47 | |
48 | A Unicode character consists either of a single code point, or a |
49 | I<base character> (like C<LATIN CAPITAL LETTER A>), followed by one or |
50 | more I<modifiers> (like C<COMBINING ACUTE ACCENT>). This sequence of |
51 | a base character and modifiers is called a I<combining character |
52 | sequence>. |
53 | |
54 | Whether to call these combining character sequences, as a whole, |
55 | "characters" depends on your point of view. If you are a programmer, you |
56 | probably would tend towards seeing each element in the sequences as one |
57 | unit, one "character", but from the user viewpoint, the sequence as a |
58 | whole is probably considered one "character", since that's probably what |
59 | it looks like in the context of the user's language. |
60 | |
61 | With this "as a whole" view of characters, the number of characters is |
62 | open-ended. But in the programmer's "one unit is one character" point of |
63 | view, the concept of "characters" is more deterministic, and so we take |
64 | that point of view in this document: one "character" is one Unicode |
65 | code point, be it a base character or a combining character. |
66 | |
67 | For some of the combinations there are I<precomposed> characters, |
68 | for example C<LATIN CAPITAL LETTER A WITH ACUTE> is defined as |
69 | a single code point. These precomposed characters are, however, |
70 | often available only for some combinations, and mainly they are |
71 | meant to support round-trip conversions between Unicode and legacy |
72 | standards (like the ISO 8859), and in general case the composing |
73 | method is more extensible. To support conversion between the |
74 | different compositions of the characters, various I<normalization |
75 | forms> are also defined. |
76 | |
77 | Because of backward compatibility with legacy encodings, the "a unique |
78 | number for every character" breaks down a bit: "at least one number |
79 | for every character" is closer to truth. (This happens when the same |
80 | character has been encoded in several legacy encodings.) The converse |
81 | is also not true: not every code point has an assigned character. |
82 | Firstly, there are unallocated code points within otherwise used |
83 | blocks. Secondly, there are special Unicode control characters that |
84 | do not represent true characters. |
85 | |
86 | A common myth about Unicode is that it would be "16-bit", that is, |
87 | 0x10000 (or 65536) characters from 0x0000 to 0xFFFF. B<This is untrue.> |
88 | Since Unicode 2.0 Unicode has been defined all the way up to 21 bits |
89 | (0x10FFFF), and since 3.1 characters have been defined beyond 0xFFFF. |
90 | The first 0x10000 characters are called the I<Plane 0>, or the I<Basic |
91 | Multilingual Plane> (BMP). With the Unicode 3.1, 17 planes in all are |
92 | defined (but nowhere near full of defined characters yet). |
93 | |
94 | Another myth is that the 256-character blocks have something to do |
95 | with languages: a block per language. B<Also this is untrue.> |
96 | The division into the blocks exists but it is almost completely |
97 | accidental, an artifact of how the characters have been historically |
98 | allocated. Instead, there is a concept called I<scripts>, which may |
99 | be more useful: there is C<Latin> script, C<Greek> script, and so on. |
100 | Scripts usually span several parts of several blocks. For further |
101 | information see L<Unicode::UCD>. |
102 | |
103 | The Unicode code points are just abstract numbers. To input and |
104 | output these abstract numbers, the numbers must be I<encoded> somehow. |
105 | Unicode defines several I<character encoding forms>, of which I<UTF-8> |
106 | is perhaps the most popular. UTF-8 is a variable length encoding that |
107 | encodes Unicode characters as 1 to 6 bytes (only 4 with the currently |
108 | defined characters). Other encodings are UTF-16 and UTF-32 and their |
109 | big and little endian variants (UTF-8 is byteorder independent). |
110 | The ISO/IEC 10646 defines the UCS-2 and UCS-4 encoding forms. |
111 | |
112 | For more information about encodings, for example to learn what |
113 | I<surrogates> and I<byte order marks> (BOMs) are, see L<perlunicode>. |
114 | |
115 | =head2 Perl's Unicode Support |
116 | |
117 | Starting from Perl 5.6.0, Perl has had the capability of handling |
118 | Unicode natively. The first recommended release for serious Unicode |
119 | work is Perl 5.8.0, however. The maintenance release 5.6.1 fixed many |
120 | of the problems of the initial implementation of Unicode, but for |
121 | example regular expressions didn't really work with Unicode. |
122 | |
123 | B<Starting from Perl 5.8.0, the use of C<use utf8> is no longer |
124 | necessary.> In earlier releases the C<utf8> pragma was used to declare |
125 | that operations in the current block or file would be Unicode-aware. |
126 | This model was found to be wrong, or at least clumsy: the Unicodeness |
127 | is now carried with the data, not attached to the operations. (There |
128 | is one remaining case where an explicit C<use utf8> is needed: if your |
129 | Perl script is in UTF-8, you can use UTF-8 in your variable and |
130 | subroutine names, and in your string and regular expression literals, |
131 | by saying C<use utf8>. This is not the default because that would |
132 | break existing scripts having legacy 8-bit data in them.) |
133 | |
134 | =head2 Perl's Unicode Model |
135 | |
136 | Perl supports both the old, pre-5.6, model of strings of eight-bit |
137 | native bytes, and strings of Unicode characters. The principle is |
138 | that Perl tries to keep its data as eight-bit bytes for as long as |
139 | possible, but as soon as Unicodeness cannot be avoided, the data is |
140 | transparently upgraded to Unicode. |
141 | |
4192de81 |
142 | Internally, Perl currently uses either whatever the native eight-bit |
143 | character set of the platform (for example Latin-1) or UTF-8 to encode |
144 | Unicode strings. Specifically, if all code points in the string are |
4049dcd4 |
145 | 0xFF or less, Perl uses the native eight-bit character set. Otherwise, it uses UTF-8. |
4192de81 |
146 | |
147 | A user of Perl does not normally need to know nor care how Perl happens |
148 | to encodes its internal strings, but it becomes relevant when outputting |
149 | Unicode strings to a stream without a discipline (one with the "default |
150 | default"). In such a case, the raw bytes used internally (the native |
151 | character set or UTF-8, as appropriate for each string) will be used, |
152 | and if warnings are turned on, a "Wide character" warning will be issued |
153 | if those strings contain a character beyond 0x00FF. |
154 | |
155 | For example, |
156 | |
157 | perl -w -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"' |
158 | |
159 | produces a fairly useless mixture of native bytes and UTF-8, as well |
160 | as a warning. |
161 | |
162 | To output UTF-8 always, use the ":utf8" output discipline. Prepending |
163 | |
164 | binmode(STDOUT, ":utf8"); |
165 | |
166 | to this sample program ensures the output is completely UTF-8, and |
4049dcd4 |
167 | of course, removes the warning. |
ba62762e |
168 | |
169 | Perl 5.8.0 will also support Unicode on EBCDIC platforms. There the |
170 | support is somewhat harder to implement since additional conversions |
171 | are needed at every step. Because of these difficulties the Unicode |
172 | support won't be quite as full as in other, mainly ASCII-based, |
173 | platforms (the Unicode support will be better than in the 5.6 series, |
174 | which didn't work much at all for EBCDIC platform). On EBCDIC |
4192de81 |
175 | platforms the internal encoding form used is UTF-EBCDIC instead |
176 | of UTF-8 (the difference is that as UTF-8 is "ASCII-safe" in that |
177 | ASCII characters encode to UTF-8 as-is, UTF-EBCDIC is "EBCDIC-safe"). |
ba62762e |
178 | |
179 | =head2 Creating Unicode |
180 | |
4192de81 |
181 | To create Unicode literals for code points above 0xFF, use the |
182 | C<\x{...}> notation in doublequoted strings: |
ba62762e |
183 | |
184 | my $smiley = "\x{263a}"; |
185 | |
186 | Similarly for regular expression literals |
187 | |
188 | $smiley =~ /\x{263a}/; |
189 | |
190 | At run-time you can use C<chr()>: |
191 | |
192 | my $hebrew_alef = chr(0x05d0); |
193 | |
194 | (See L</"Further Resources"> for how to find all these numeric codes.) |
195 | |
196 | Naturally, C<ord()> will do the reverse: turn a character to a code point. |
197 | |
8a5e5dd5 |
198 | Note that C<\x..> (no C<{}> and only two hexadecimal digits), C<\x{...}> |
199 | and C<chr(...)> for arguments less than 0x100 (decimal 256) will |
200 | generate an eight-bit character for backward compatibility with older |
201 | Perls. For arguments of 0x100 or more, Unicode will always be |
202 | produced. If you want UTF-8 always, use C<pack("U", ...)> instead of |
203 | C<\x..>, C<\x{...}>, or C<chr()>. |
ba62762e |
204 | |
205 | You can also use the C<charnames> pragma to invoke characters |
206 | by name in doublequoted strings: |
207 | |
208 | use charnames ':full'; |
209 | my $arabic_alef = "\N{ARABIC LETTER ALEF}"; |
210 | |
211 | And, as mentioned above, you can also C<pack()> numbers into Unicode |
212 | characters: |
213 | |
214 | my $georgian_an = pack("U", 0x10a0); |
215 | |
8a5e5dd5 |
216 | Note that both C<\x{...}> and C<\N{...}> are compile-time string |
217 | constants: you cannot use variables in them. if you want similar |
218 | run-time functionality, use C<chr()> and C<charnames::vianame()>. |
219 | |
ba62762e |
220 | =head2 Handling Unicode |
221 | |
222 | Handling Unicode is for the most part transparent: just use the |
223 | strings as usual. Functions like C<index()>, C<length()>, and |
224 | C<substr()> will work on the Unicode characters; regular expressions |
225 | will work on the Unicode characters (see L<perlunicode> and L<perlretut>). |
226 | |
227 | Note that Perl does B<not> consider combining character sequences |
228 | to be characters, such for example |
229 | |
230 | use charnames ':full'; |
231 | print length("\N{LATIN CAPITAL LETTER A}\N{COMBINING ACUTE ACCENT}"), "\n"; |
232 | |
233 | will print 2, not 1. The only exception is that regular expressions |
234 | have C<\X> for matching a combining character sequence. |
235 | |
236 | When life is not quite so transparent is working with legacy |
237 | encodings, and I/O, and certain special cases. |
238 | |
239 | =head2 Legacy Encodings |
240 | |
241 | When you combine legacy data and Unicode the legacy data needs |
242 | to be upgraded to Unicode. Normally ISO 8859-1 (or EBCDIC, if |
243 | applicable) is assumed. You can override this assumption by |
244 | using the C<encoding> pragma, for example |
245 | |
246 | use encoding 'latin2'; # ISO 8859-2 |
247 | |
248 | in which case literals (string or regular expression) and chr/ord |
249 | in your whole script are assumed to produce Unicode characters from |
250 | ISO 8859-2 code points. Note that the matching for the encoding |
251 | names is forgiving: instead of C<latin2> you could have said |
252 | C<Latin 2>, or C<iso8859-2>, and so forth. With just |
253 | |
254 | use encoding; |
255 | |
256 | first the environment variable C<PERL_ENCODING> will be consulted, |
257 | and if that doesn't exist, ISO 8859-1 (Latin 1) will be assumed. |
258 | |
259 | The C<Encode> module knows about many encodings and it has interfaces |
260 | for doing conversions between those encodings: |
261 | |
262 | use Encode 'from_to'; |
263 | from_to($data, "iso-8859-3", "utf-8"); # from legacy to utf-8 |
264 | |
265 | =head2 Unicode I/O |
266 | |
267 | Normally writing out Unicode data |
268 | |
1d7919c5 |
269 | print FH chr(0x100), "\n"; |
ba62762e |
270 | |
1d7919c5 |
271 | will print out the raw UTF-8 bytes, but you will get a warning |
272 | out of that if you use C<-w> or C<use warnings>. To avoid the |
273 | warning open the stream explicitly in UTF-8: |
ba62762e |
274 | |
1d7919c5 |
275 | open FH, ">:utf8", "file"; |
276 | |
277 | and on already open streams use C<binmode()>: |
278 | |
279 | binmode(STDOUT, ":utf8"); |
280 | |
281 | Reading in correctly formed UTF-8 data will not magically turn |
ba62762e |
282 | the data into Unicode in Perl's eyes. |
283 | |
284 | You can use either the C<':utf8'> I/O discipline when opening files |
285 | |
286 | open(my $fh,'<:utf8', 'anything'); |
287 | my $line_of_utf8 = <$fh>; |
288 | |
289 | The I/O disciplines can also be specified more flexibly with |
290 | the C<open> pragma; see L<open>: |
291 | |
1d7919c5 |
292 | use open ':utf8'; # input and output default discipline will be UTF-8 |
293 | open X, ">file"; |
294 | print X chr(0x100), "\n"; |
ba62762e |
295 | close X; |
1d7919c5 |
296 | open Y, "<file"; |
ba62762e |
297 | printf "%#x\n", ord(<Y>); # this should print 0x100 |
298 | close Y; |
299 | |
300 | With the C<open> pragma you can use the C<:locale> discipline |
301 | |
1ecefa54 |
302 | $ENV{LC_ALL} = $ENV{LANG} = 'ru_RU.KOI8-R'; |
303 | # the :locale will probe the locale environment variables like LC_ALL |
ba62762e |
304 | use open OUT => ':locale'; # russki parusski |
305 | open(O, ">koi8"); |
306 | print O chr(0x430); # Unicode CYRILLIC SMALL LETTER A = KOI8-R 0xc1 |
307 | close O; |
308 | open(I, "<koi8"); |
309 | printf "%#x\n", ord(<I>), "\n"; # this should print 0xc1 |
310 | close I; |
311 | |
312 | or you can also use the C<':encoding(...)'> discipline |
313 | |
314 | open(my $epic,'<:encoding(iso-8859-7)','iliad.greek'); |
315 | my $line_of_iliad = <$epic>; |
316 | |
317 | Both of these methods install a transparent filter on the I/O stream that |
318 | will convert data from the specified encoding when it is read in from the |
319 | stream. In the first example the F<anything> file is assumed to be UTF-8 |
320 | encoded Unicode, in the second example the F<iliad.greek> file is assumed |
321 | to be ISO-8858-7 encoded Greek, but the lines read in will be in both |
322 | cases Unicode. |
323 | |
324 | The L<open> pragma affects all the C<open()> calls after the pragma by |
325 | setting default disciplines. If you want to affect only certain |
326 | streams, use explicit disciplines directly in the C<open()> call. |
327 | |
328 | You can switch encodings on an already opened stream by using |
329 | C<binmode()>, see L<perlfunc/binmode>. |
330 | |
1ecefa54 |
331 | The C<:locale> does not currently (as of Perl 5.8.0) work with |
332 | C<open()> and C<binmode()>, only with the C<open> pragma. The |
333 | C<:utf8> and C<:encoding(...)> do work with all of C<open()>, |
334 | C<binmode()>, and the C<open> pragma. |
ba62762e |
335 | |
336 | Similarly, you may use these I/O disciplines on input streams to |
337 | automatically convert data from the specified encoding when it is |
338 | written to the stream. |
339 | |
340 | open(my $unicode, '<:utf8', 'japanese.uni'); |
341 | open(my $nihongo, '>:encoding(iso2022-jp)', 'japanese.jp'); |
342 | while (<$unicode>) { print $nihongo } |
343 | |
344 | The naming of encodings, both by the C<open()> and by the C<open> |
345 | pragma, is similarly understanding as with the C<encoding> pragma: |
346 | C<koi8-r> and C<KOI8R> will both be understood. |
347 | |
348 | Common encodings recognized by ISO, MIME, IANA, and various other |
349 | standardisation organisations are recognised, for a more detailed |
350 | list see L<Encode>. |
351 | |
352 | C<read()> reads characters and returns the number of characters. |
353 | C<seek()> and C<tell()> operate on byte counts, as do C<sysread()> |
354 | and C<sysseek()>. |
355 | |
356 | Notice that because of the default behaviour "input is not UTF-8" |
357 | it is easy to mistakenly write code that keeps on expanding a file |
358 | by repeatedly encoding it in UTF-8: |
359 | |
360 | # BAD CODE WARNING |
361 | open F, "file"; |
362 | local $/; # read in the whole file |
363 | $t = <F>; |
364 | close F; |
365 | open F, ">:utf8", "file"; |
366 | print F $t; |
367 | close F; |
368 | |
369 | If you run this code twice, the contents of the F<file> will be twice |
1d7919c5 |
370 | UTF-8 encoded. A C<use open ':utf8'> would have avoided the bug, or |
371 | explicitly opening also the F<file> for input as UTF-8. |
ba62762e |
372 | |
0c901d84 |
373 | B<NOTE>: the C<:utf8> and C<:encoding> features work only if your |
374 | Perl has been built with the new "perlio" feature. Almost all |
375 | Perl 5.8 platforms do use "perlio", though: you can see whether |
376 | yours is by running "perl -V" and looking for C<useperlio=define>. |
377 | |
1ecefa54 |
378 | =head2 Displaying Unicode As Text |
379 | |
380 | Sometimes you might want to display Perl scalars containing Unicode as |
381 | simple ASCII (or EBCDIC) text. The following subroutine will convert |
382 | its argument so that Unicode characters with code points greater than |
383 | 255 are displayed as "\x{...}", control characters (like "\n") are |
384 | displayed as "\x..", and the rest of the characters as themselves. |
385 | |
58c274a1 |
386 | sub nice_string { |
387 | join("", |
388 | map { $_ > 255 ? # if wide character... |
389 | sprintf("\\x{%x}", $_) : # \x{...} |
390 | chr($_) =~ /[[:cntrl:]]/ ? # else if control character ... |
391 | sprintf("\\x%02x", $_) : # \x.. |
392 | chr($_) # else as themselves |
393 | } unpack("U*", $_[0])); # unpack Unicode characters |
394 | } |
395 | |
396 | For example, |
397 | |
398 | nice_string("foo\x{100}bar\n") |
399 | |
400 | will return: |
401 | |
402 | "foo\x{100}bar\x0a" |
1ecefa54 |
403 | |
ba62762e |
404 | =head2 Special Cases |
405 | |
406 | =over 4 |
407 | |
408 | =item * |
409 | |
410 | Bit Complement Operator ~ And vec() |
411 | |
412 | The bit complement operator C<~> will produce surprising results if |
413 | used on strings containing Unicode characters. The results are |
414 | consistent with the internal UTF-8 encoding of the characters, but not |
415 | with much else. So don't do that. Similarly for vec(): you will be |
416 | operating on the UTF-8 bit patterns of the Unicode characters, not on |
417 | the bytes, which is very probably not what you want. |
418 | |
419 | =item * |
420 | |
421 | Peeking At UTF-8 |
422 | |
423 | One way of peeking inside the internal encoding of Unicode characters |
424 | is to use C<unpack("C*", ...> to get the bytes, or C<unpack("H*", ...)> |
425 | to display the bytes: |
426 | |
427 | # this will print c4 80 for the UTF-8 bytes 0xc4 0x80 |
428 | print join(" ", unpack("H*", pack("U", 0x100))), "\n"; |
429 | |
430 | Yet another way would be to use the Devel::Peek module: |
431 | |
432 | perl -MDevel::Peek -e 'Dump(chr(0x100))' |
433 | |
434 | That will show the UTF8 flag in FLAGS and both the UTF-8 bytes |
435 | and Unicode characters in PV. See also later in this document |
436 | the discussion about the C<is_utf8> function of the C<Encode> module. |
437 | |
438 | =back |
439 | |
440 | =head2 Advanced Topics |
441 | |
442 | =over 4 |
443 | |
444 | =item * |
445 | |
446 | String Equivalence |
447 | |
448 | The question of string equivalence turns somewhat complicated |
449 | in Unicode: what do you mean by equal? |
450 | |
07698885 |
451 | (Is C<LATIN CAPITAL LETTER A WITH ACUTE> equal to |
452 | C<LATIN CAPITAL LETTER A>?) |
ba62762e |
453 | |
454 | The short answer is that by default Perl compares equivalence |
455 | (C<eq>, C<ne>) based only on code points of the characters. |
58c274a1 |
456 | In the above case, the answer is no (because 0x00C1 != 0x0041). But sometimes any |
ba62762e |
457 | CAPITAL LETTER As being considered equal, or even any As of any case, |
458 | would be desirable. |
459 | |
460 | The long answer is that you need to consider character normalization |
461 | and casing issues: see L<Unicode::Normalize>, and Unicode Technical |
462 | Reports #15 and #21, I<Unicode Normalization Forms> and I<Case |
463 | Mappings>, http://www.unicode.org/unicode/reports/tr15/ |
464 | http://www.unicode.org/unicode/reports/tr21/ |
465 | |
58c274a1 |
466 | As of Perl 5.8.0, regular expression case-ignoring matching |
ba62762e |
467 | implements only 1:1 semantics: one character matches one character. |
468 | In I<Case Mappings> both 1:N and N:1 matches are defined. |
469 | |
470 | =item * |
471 | |
472 | String Collation |
473 | |
474 | People like to see their strings nicely sorted, or as Unicode |
475 | parlance goes, collated. But again, what do you mean by collate? |
476 | |
07698885 |
477 | (Does C<LATIN CAPITAL LETTER A WITH ACUTE> come before or after |
478 | C<LATIN CAPITAL LETTER A WITH GRAVE>?) |
ba62762e |
479 | |
58c274a1 |
480 | The short answer is that by default, Perl compares strings (C<lt>, |
ba62762e |
481 | C<le>, C<cmp>, C<ge>, C<gt>) based only on the code points of the |
58c274a1 |
482 | characters. In the above case, the answer is "after", since 0x00C1 > 0x00C0. |
ba62762e |
483 | |
484 | The long answer is that "it depends", and a good answer cannot be |
485 | given without knowing (at the very least) the language context. |
486 | See L<Unicode::Collate>, and I<Unicode Collation Algorithm> |
487 | http://www.unicode.org/unicode/reports/tr10/ |
488 | |
489 | =back |
490 | |
491 | =head2 Miscellaneous |
492 | |
493 | =over 4 |
494 | |
495 | =item * |
496 | |
497 | Character Ranges |
498 | |
499 | Character ranges in regular expression character classes (C</[a-z]/>) |
500 | and in the C<tr///> (also known as C<y///>) operator are not magically |
58c274a1 |
501 | Unicode-aware. What this means that C<[A-Za-z]> will not magically start |
ba62762e |
502 | to mean "all alphabetic letters" (not that it does mean that even for |
503 | 8-bit characters, you should be using C</[[:alpha]]/> for that). |
504 | |
58c274a1 |
505 | For specifying things like that in regular expressions, you can use the |
506 | various Unicode properties, C<\pL> or perhaps C<\p{Alphabetic}>, in this particular case. You can |
ba62762e |
507 | use Unicode code points as the end points of character ranges, but |
508 | that means that particular code point range, nothing more. For |
509 | further information, see L<perlunicode>. |
510 | |
511 | =item * |
512 | |
513 | String-To-Number Conversions |
514 | |
515 | Unicode does define several other decimal (and numeric) characters |
516 | than just the familiar 0 to 9, such as the Arabic and Indic digits. |
517 | Perl does not support string-to-number conversion for digits other |
58c274a1 |
518 | than ASCII 0 to 9 (and ASCII a to f for hexadecimal). |
ba62762e |
519 | |
520 | =back |
521 | |
522 | =head2 Questions With Answers |
523 | |
524 | =over 4 |
525 | |
526 | =item Will My Old Scripts Break? |
527 | |
528 | Very probably not. Unless you are generating Unicode characters |
529 | somehow, any old behaviour should be preserved. About the only |
530 | behaviour that has changed and which could start generating Unicode |
531 | is the old behaviour of C<chr()> where supplying an argument more |
532 | than 255 produced a character modulo 255 (for example, C<chr(300)> |
533 | was equal to C<chr(45)>). |
534 | |
535 | =item How Do I Make My Scripts Work With Unicode? |
536 | |
537 | Very little work should be needed since nothing changes until you |
538 | somehow generate Unicode data. The greatest trick will be getting |
539 | input as Unicode, and for that see the earlier I/O discussion. |
540 | |
541 | =item How Do I Know Whether My String Is In Unicode? |
542 | |
543 | You shouldn't care. No, you really shouldn't. If you have |
544 | to care (beyond the cases described above), it means that we |
545 | didn't get the transparency of Unicode quite right. |
546 | |
547 | Okay, if you insist: |
548 | |
549 | use Encode 'is_utf8'; |
550 | print is_utf8($string) ? 1 : 0, "\n"; |
551 | |
552 | But note that this doesn't mean that any of the characters in the |
553 | string are necessary UTF-8 encoded, or that any of the characters have |
554 | code points greater than 0xFF (255) or even 0x80 (128), or that the |
555 | string has any characters at all. All the C<is_utf8()> does is to |
556 | return the value of the internal "utf8ness" flag attached to the |
557 | $string. If the flag is on, characters added to that string will be |
558 | automatically upgraded to UTF-8 (and even then only if they really |
559 | need to be upgraded, that is, if their code point is greater than 0xFF). |
560 | |
561 | Sometimes you might really need to know the byte length of a string |
562 | instead of the character length. For that use the C<bytes> pragma |
563 | and its only defined function C<length()>: |
564 | |
565 | my $unicode = chr(0x100); |
566 | print length($unicode), "\n"; # will print 1 |
567 | use bytes; |
568 | print length($unicode), "\n"; # will print 2 (the 0xC4 0x80 of the UTF-8) |
569 | |
570 | =item How Do I Detect Invalid UTF-8? |
571 | |
572 | Either |
573 | |
574 | use Encode 'encode_utf8'; |
575 | if (encode_utf8($string)) { |
576 | # valid |
577 | } else { |
578 | # invalid |
579 | } |
580 | |
581 | or |
582 | |
583 | use warnings; |
584 | @chars = unpack("U0U*", "\xFF"); # will warn |
585 | |
586 | The warning will be C<Malformed UTF-8 character (byte 0xff) in |
587 | unpack>. The "U0" means "expect strictly UTF-8 encoded Unicode". |
588 | Without that the C<unpack("U*", ...)> would accept also data like |
589 | C<chr(0xFF>). |
590 | |
591 | =item How Do I Convert Data Into UTF-8? Or Vice Versa? |
592 | |
593 | This probably isn't as useful (or simple) as you might think. |
594 | Also, normally you shouldn't need to. |
595 | |
596 | In one sense what you are asking doesn't make much sense: UTF-8 is |
597 | (intended as an) Unicode encoding, so converting "data" into UTF-8 |
598 | isn't meaningful unless you know in what character set and encoding |
599 | the binary data is in, and in this case you can use C<Encode>. |
600 | |
601 | use Encode 'from_to'; |
602 | from_to($data, "iso-8859-1", "utf-8"); # from latin-1 to utf-8 |
603 | |
604 | If you have ASCII (really 7-bit US-ASCII), you already have valid |
605 | UTF-8, the lowest 128 characters of UTF-8 encoded Unicode and US-ASCII |
606 | are equivalent. |
607 | |
608 | If you have Latin-1 (or want Latin-1), you can just use pack/unpack: |
609 | |
610 | $latin1 = pack("C*", unpack("U*", $utf8)); |
611 | $utf8 = pack("U*", unpack("C*", $latin1)); |
612 | |
613 | (The same works for EBCDIC.) |
614 | |
615 | If you have a sequence of bytes you B<know> is valid UTF-8, |
616 | but Perl doesn't know it yet, you can make Perl a believer, too: |
617 | |
618 | use Encode 'decode_utf8'; |
619 | $utf8 = decode_utf8($bytes); |
620 | |
621 | You can convert well-formed UTF-8 to a sequence of bytes, but if |
622 | you just want to convert random binary data into UTF-8, you can't. |
623 | Any random collection of bytes isn't well-formed UTF-8. You can |
624 | use C<unpack("C*", $string)> for the former, and you can create |
625 | well-formed Unicode/UTF-8 data by C<pack("U*", 0xff, ...)>. |
626 | |
627 | =item How Do I Display Unicode? How Do I Input Unicode? |
628 | |
629 | See http://www.hclrss.demon.co.uk/unicode/ and |
630 | http://www.cl.cam.ac.uk/~mgk25/unicode.html |
631 | |
632 | =item How Does Unicode Work With Traditional Locales? |
633 | |
634 | In Perl, not very well. Avoid using locales through the C<locale> |
635 | pragma. Use only one or the other. |
636 | |
637 | =back |
638 | |
639 | =head2 Hexadecimal Notation |
640 | |
641 | The Unicode standard prefers using hexadecimal notation because that |
642 | shows better the division of Unicode into blocks of 256 characters. |
643 | Hexadecimal is also simply shorter than decimal. You can use decimal |
644 | notation, too, but learning to use hexadecimal just makes life easier |
645 | with the Unicode standard. |
646 | |
647 | The C<0x> prefix means a hexadecimal number, the digits are 0-9 I<and> |
648 | a-f (or A-F, case doesn't matter). Each hexadecimal digit represents |
649 | four bits, or half a byte. C<print 0x..., "\n"> will show a |
650 | hexadecimal number in decimal, and C<printf "%x\n", $decimal> will |
651 | show a decimal number in hexadecimal. If you have just the |
652 | "hexdigits" of a hexadecimal number, you can use the C<hex()> |
653 | function. |
654 | |
655 | print 0x0009, "\n"; # 9 |
656 | print 0x000a, "\n"; # 10 |
657 | print 0x000f, "\n"; # 15 |
658 | print 0x0010, "\n"; # 16 |
659 | print 0x0011, "\n"; # 17 |
660 | print 0x0100, "\n"; # 256 |
661 | |
662 | print 0x0041, "\n"; # 65 |
663 | |
664 | printf "%x\n", 65; # 41 |
665 | printf "%#x\n", 65; # 0x41 |
666 | |
667 | print hex("41"), "\n"; # 65 |
668 | |
669 | =head2 Further Resources |
670 | |
671 | =over 4 |
672 | |
673 | =item * |
674 | |
675 | Unicode Consortium |
676 | |
677 | http://www.unicode.org/ |
678 | |
679 | =item * |
680 | |
681 | Unicode FAQ |
682 | |
683 | http://www.unicode.org/unicode/faq/ |
684 | |
685 | =item * |
686 | |
687 | Unicode Glossary |
688 | |
689 | http://www.unicode.org/glossary/ |
690 | |
691 | =item * |
692 | |
693 | Unicode Useful Resources |
694 | |
695 | http://www.unicode.org/unicode/onlinedat/resources.html |
696 | |
697 | =item * |
698 | |
699 | Unicode and Multilingual Support in HTML, Fonts, Web Browsers and Other Applications |
700 | |
701 | http://www.hclrss.demon.co.uk/unicode/ |
702 | |
703 | =item * |
704 | |
705 | UTF-8 and Unicode FAQ for Unix/Linux |
706 | |
707 | http://www.cl.cam.ac.uk/~mgk25/unicode.html |
708 | |
709 | =item * |
710 | |
711 | Legacy Character Sets |
712 | |
713 | http://www.czyborra.com/ |
714 | http://www.eki.ee/letter/ |
715 | |
716 | =item * |
717 | |
718 | The Unicode support files live within the Perl installation in the |
719 | directory |
720 | |
721 | $Config{installprivlib}/unicore |
722 | |
723 | in Perl 5.8.0 or newer, and |
724 | |
725 | $Config{installprivlib}/unicode |
726 | |
727 | in the Perl 5.6 series. (The renaming to F<lib/unicore> was done to |
728 | avoid naming conflicts with lib/Unicode in case-insensitive filesystems.) |
729 | The main Unicode data file is F<Unicode.txt> (or F<Unicode.301> in |
730 | Perl 5.6.1.) You can find the C<$Config{installprivlib}> by |
731 | |
732 | perl "-V:installprivlib" |
733 | |
734 | Note that some of the files have been renamed from the Unicode |
735 | standard since the Perl installation tries to live by the "8.3" |
736 | filenaming restrictions. The renamings are shown in the |
737 | accompanying F<rename> file. |
738 | |
739 | You can explore various information from the Unicode data files using |
740 | the C<Unicode::UCD> module. |
741 | |
742 | =back |
743 | |
f6edf83b |
744 | =head1 UNICODE IN OLDER PERLS |
745 | |
746 | If you cannot upgrade your Perl to 5.8.0 or later, you can still |
747 | do some Unicode processing by using the modules C<Unicode::String>, |
748 | C<Unicode::Map8>, and C<Unicode::Map>, available from CPAN. |
749 | If you have the GNU recode installed, you can also use the |
750 | Perl frontend C<Convert::Recode> for character conversions. |
751 | |
ba62762e |
752 | =head1 SEE ALSO |
753 | |
754 | L<perlunicode>, L<Encode>, L<encoding>, L<open>, L<utf8>, L<bytes>, |
755 | L<perlretut>, L<Unicode::Collate>, L<Unicode::Normalize>, L<Unicode::UCD> |
756 | |
757 | =head1 ACKNOWLEDGEMENTS |
758 | |
759 | Thanks to the kind readers of the perl5-porters@perl.org, |
760 | perl-unicode@perl.org, linux-utf8@nl.linux.org, and unicore@unicode.org |
761 | mailing lists for their valuable feedback. |
762 | |
763 | =head1 AUTHOR, COPYRIGHT, AND LICENSE |
764 | |
765 | Copyright 2001 Jarkko Hietaniemi <jhi@iki.fi> |
766 | |
767 | This document may be distributed under the same terms as Perl itself. |