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