This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
pod/perluniintro.pod (removes unnecessary UTF-8 references)
[perl5.git] / pod / perluniintro.pod
CommitLineData
ba62762e
JH
1=head1 NAME
2
07fcf8ff 3perluniintro - Perl Unicode introduction
ba62762e
JH
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
8baee566 108defined characters). Other encodings include UTF-16 and UTF-32 and their
ba62762e
JH
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
8baee566 129Perl script itself is encoded in UTF-8, you can use UTF-8 in your variable and
ba62762e
JH
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
JH
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
4049dcd4 1450xFF or less, Perl uses the native eight-bit character set. Otherwise, it uses UTF-8.
4192de81
JH
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
4049dcd4 167of course, removes the warning.
ba62762e 168
8baee566 169Perl 5.8.0 also supports Unicode on EBCDIC platforms. There, the
ba62762e 170support is somewhat harder to implement since additional conversions
8baee566
JF
171are needed at every step. Because of these difficulties, the Unicode
172support isn't quite as full as in other, mainly ASCII-based,
173platforms (the Unicode support is better than in the 5.6 series,
ba62762e 174which didn't work much at all for EBCDIC platform). On EBCDIC
8baee566 175platforms, the internal Unicode encoding form is UTF-EBCDIC instead
4192de81
JH
176of UTF-8 (the difference is that as UTF-8 is "ASCII-safe" in that
177ASCII characters encode to UTF-8 as-is, UTF-EBCDIC is "EBCDIC-safe").
ba62762e
JH
178
179=head2 Creating Unicode
180
8baee566 181To create Unicode characters in literals for code points above 0xFF, use the
4192de81 182C<\x{...}> notation in doublequoted strings:
ba62762e
JH
183
184 my $smiley = "\x{263a}";
185
8baee566 186Similarly in regular expression literals
ba62762e
JH
187
188 $smiley =~ /\x{263a}/;
189
190At 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
196Naturally, C<ord()> will do the reverse: turn a character to a code point.
197
8baee566
JF
198Note that C<\x..> (no C<{}> and only two hexadecimal digits), C<\x{...}>,
199and C<chr(...)> for arguments less than 0x100 (decimal 256)
8a5e5dd5 200generate an eight-bit character for backward compatibility with older
8baee566
JF
201Perls. For arguments of 0x100 or more, Unicode characters are always
202produced. If you want to force the production of Unicode characters
203regardless of the numeric value, use C<pack("U", ...)> instead of C<\x..>,
204C<\x{...}>, or C<chr()>.
ba62762e
JH
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
JH
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
JH
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
8baee566 268Normally, writing out Unicode data
ba62762e 269
8baee566 270 print FH $some_string_with_unicode, "\n";
ba62762e 271
8baee566
JF
272produces raw bytes that Perl happens to use to internally encode the
273Unicode string (which depends on the system, as well as what characters
274happen to be in the string at the time). If any of the characters are at
275code points 0x100 or above, you will get a warning if you use C<-w> or C<use
276warnings>. To ensure that the output is explicitly rendered in the encoding
277you desire (and to avoid the warning), open the stream with the desired
278encoding. Some examples:
ba62762e 279
8baee566
JF
280 open FH, ">:ucs2", "file"
281 open FH, ">:utf8", "file";
282 open FH, ">:Shift-JIS", "file";
1d7919c5
JH
283
284and on already open streams use C<binmode()>:
285
8baee566 286 binmode(STDOUT, ":ucs2");
1d7919c5 287 binmode(STDOUT, ":utf8");
8baee566 288 binmode(STDOUT, ":Shift-JIS");
1d7919c5 289
8baee566 290See documentation for the C<Encode> module for many supported encodings.
ba62762e 291
8baee566
JF
292Reading in a file that you know happens to be encoded in one of the Unicode
293encodings does not magically turn the data into Unicode in Perl's eyes.
294To do that, specify the appropriate discipline when opening files
ba62762e
JH
295
296 open(my $fh,'<:utf8', 'anything');
8baee566
JF
297 my $line_of_unicode = <$fh>;
298
299 open(my $fh,'<:Big5', 'anything');
300 my $line_of_unicode = <$fh>;
ba62762e
JH
301
302The I/O disciplines can also be specified more flexibly with
303the C<open> pragma; see L<open>:
304
1d7919c5
JH
305 use open ':utf8'; # input and output default discipline will be UTF-8
306 open X, ">file";
307 print X chr(0x100), "\n";
ba62762e 308 close X;
1d7919c5 309 open Y, "<file";
ba62762e
JH
310 printf "%#x\n", ord(<Y>); # this should print 0x100
311 close Y;
312
313With the C<open> pragma you can use the C<:locale> discipline
314
1ecefa54
JH
315 $ENV{LC_ALL} = $ENV{LANG} = 'ru_RU.KOI8-R';
316 # the :locale will probe the locale environment variables like LC_ALL
ba62762e
JH
317 use open OUT => ':locale'; # russki parusski
318 open(O, ">koi8");
319 print O chr(0x430); # Unicode CYRILLIC SMALL LETTER A = KOI8-R 0xc1
320 close O;
321 open(I, "<koi8");
322 printf "%#x\n", ord(<I>), "\n"; # this should print 0xc1
323 close I;
324
325or you can also use the C<':encoding(...)'> discipline
326
327 open(my $epic,'<:encoding(iso-8859-7)','iliad.greek');
8baee566 328 my $line_of_unicode = <$epic>;
ba62762e 329
8baee566
JF
330These methods install a transparent filter on the I/O stream that
331converts data from the specified encoding when it is read in from the
332stream. The result is always Unicode
ba62762e
JH
333
334The L<open> pragma affects all the C<open()> calls after the pragma by
335setting default disciplines. If you want to affect only certain
336streams, use explicit disciplines directly in the C<open()> call.
337
338You can switch encodings on an already opened stream by using
8baee566 339C<binmode()>; see L<perlfunc/binmode>.
ba62762e 340
1ecefa54
JH
341The C<:locale> does not currently (as of Perl 5.8.0) work with
342C<open()> and C<binmode()>, only with the C<open> pragma. The
8baee566 343C<:utf8> and C<:encoding(...)> methods do work with all of C<open()>,
1ecefa54 344C<binmode()>, and the C<open> pragma.
ba62762e 345
8baee566
JF
346Similarly, you may use these I/O disciplines on output streams to
347automatically convert Unicode to the specified encoding when it is written
348to the stream. For example, the following snippet copies the contents of
349the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to the file
350"text.utf8", encoded as UTF-8:
ba62762e 351
8baee566
JF
352 open(my $nihongo, '<:encoding(iso2022-jp)', 'text.jis');
353 open(my $unicode, '>:utf8', 'text.utf8');
354 while (<$nihongo>) { print $unicode }
ba62762e
JH
355
356The naming of encodings, both by the C<open()> and by the C<open>
357pragma, is similarly understanding as with the C<encoding> pragma:
358C<koi8-r> and C<KOI8R> will both be understood.
359
360Common encodings recognized by ISO, MIME, IANA, and various other
8baee566 361standardisation organisations are recognised; for a more detailed
ba62762e
JH
362list see L<Encode>.
363
364C<read()> reads characters and returns the number of characters.
365C<seek()> and C<tell()> operate on byte counts, as do C<sysread()>
366and C<sysseek()>.
367
8baee566
JF
368Notice that because of the default behaviour of not doing any
369conversion upon input if there is no default discipline,
ba62762e 370it is easy to mistakenly write code that keeps on expanding a file
8baee566 371by repeatedly encoding:
ba62762e
JH
372
373 # BAD CODE WARNING
374 open F, "file";
8baee566 375 local $/; ## read in the whole file of 8-bit characters
ba62762e
JH
376 $t = <F>;
377 close F;
378 open F, ">:utf8", "file";
8baee566 379 print F $t; ## convert to UTF-8 on output
ba62762e
JH
380 close F;
381
382If you run this code twice, the contents of the F<file> will be twice
1d7919c5
JH
383UTF-8 encoded. A C<use open ':utf8'> would have avoided the bug, or
384explicitly opening also the F<file> for input as UTF-8.
ba62762e 385
0c901d84
JH
386B<NOTE>: the C<:utf8> and C<:encoding> features work only if your
387Perl has been built with the new "perlio" feature. Almost all
388Perl 5.8 platforms do use "perlio", though: you can see whether
389yours is by running "perl -V" and looking for C<useperlio=define>.
390
1ecefa54
JH
391=head2 Displaying Unicode As Text
392
393Sometimes you might want to display Perl scalars containing Unicode as
8baee566 394simple ASCII (or EBCDIC) text. The following subroutine converts
1ecefa54
JH
395its argument so that Unicode characters with code points greater than
396255 are displayed as "\x{...}", control characters (like "\n") are
8baee566 397displayed as "\x..", and the rest of the characters as themselves:
1ecefa54 398
58c274a1
JF
399 sub nice_string {
400 join("",
401 map { $_ > 255 ? # if wide character...
8baee566 402 sprintf("\\x{%04X}", $_) : # \x{...}
58c274a1 403 chr($_) =~ /[[:cntrl:]]/ ? # else if control character ...
8baee566 404 sprintf("\\x%02X", $_) : # \x..
58c274a1
JF
405 chr($_) # else as themselves
406 } unpack("U*", $_[0])); # unpack Unicode characters
407 }
408
409For example,
410
411 nice_string("foo\x{100}bar\n")
412
8baee566 413returns:
58c274a1 414
8baee566 415 "foo\x{0100}bar\x0A"
1ecefa54 416
ba62762e
JH
417=head2 Special Cases
418
419=over 4
420
421=item *
422
423Bit Complement Operator ~ And vec()
424
8baee566 425The bit complement operator C<~> may produce surprising results if
ba62762e 426used on strings containing Unicode characters. The results are
8baee566 427consistent with the internal encoding of the characters, but not
ba62762e 428with much else. So don't do that. Similarly for vec(): you will be
8baee566
JF
429operating on the internally encoded bit patterns of the Unicode characters, not on
430the code point values, which is very probably not what you want.
ba62762e
JH
431
432=item *
433
8baee566
JF
434Peeking At Perl's Internal Encoding
435
436Normal users of Perl should never care how Perl encodes any particular
437Unicode string (because the normal ways to get at the contents of a string
438with Unicode -- via input and output -- should always be via
439explicitly-defined I/O disciplines). But if you must, there are two ways of
440looking behind the scenes.
ba62762e
JH
441
442One way of peeking inside the internal encoding of Unicode characters
443is to use C<unpack("C*", ...> to get the bytes, or C<unpack("H*", ...)>
444to display the bytes:
445
8baee566 446 # this prints c4 80 for the UTF-8 bytes 0xc4 0x80
ba62762e
JH
447 print join(" ", unpack("H*", pack("U", 0x100))), "\n";
448
449Yet another way would be to use the Devel::Peek module:
450
451 perl -MDevel::Peek -e 'Dump(chr(0x100))'
452
8baee566 453That shows the UTF8 flag in FLAGS and both the UTF-8 bytes
ba62762e
JH
454and Unicode characters in PV. See also later in this document
455the discussion about the C<is_utf8> function of the C<Encode> module.
456
457=back
458
459=head2 Advanced Topics
460
461=over 4
462
463=item *
464
465String Equivalence
466
467The question of string equivalence turns somewhat complicated
468in Unicode: what do you mean by equal?
469
07698885
RGS
470(Is C<LATIN CAPITAL LETTER A WITH ACUTE> equal to
471C<LATIN CAPITAL LETTER A>?)
ba62762e
JH
472
473The short answer is that by default Perl compares equivalence
474(C<eq>, C<ne>) based only on code points of the characters.
58c274a1 475In the above case, the answer is no (because 0x00C1 != 0x0041). But sometimes any
ba62762e
JH
476CAPITAL LETTER As being considered equal, or even any As of any case,
477would be desirable.
478
479The long answer is that you need to consider character normalization
480and casing issues: see L<Unicode::Normalize>, and Unicode Technical
481Reports #15 and #21, I<Unicode Normalization Forms> and I<Case
482Mappings>, http://www.unicode.org/unicode/reports/tr15/
483http://www.unicode.org/unicode/reports/tr21/
484
58c274a1 485As of Perl 5.8.0, regular expression case-ignoring matching
ba62762e
JH
486implements only 1:1 semantics: one character matches one character.
487In I<Case Mappings> both 1:N and N:1 matches are defined.
488
489=item *
490
491String Collation
492
493People like to see their strings nicely sorted, or as Unicode
494parlance goes, collated. But again, what do you mean by collate?
495
07698885
RGS
496(Does C<LATIN CAPITAL LETTER A WITH ACUTE> come before or after
497C<LATIN CAPITAL LETTER A WITH GRAVE>?)
ba62762e 498
58c274a1 499The short answer is that by default, Perl compares strings (C<lt>,
ba62762e 500C<le>, C<cmp>, C<ge>, C<gt>) based only on the code points of the
58c274a1 501characters. In the above case, the answer is "after", since 0x00C1 > 0x00C0.
ba62762e
JH
502
503The long answer is that "it depends", and a good answer cannot be
504given without knowing (at the very least) the language context.
505See L<Unicode::Collate>, and I<Unicode Collation Algorithm>
506http://www.unicode.org/unicode/reports/tr10/
507
508=back
509
510=head2 Miscellaneous
511
512=over 4
513
514=item *
515
516Character Ranges
517
518Character ranges in regular expression character classes (C</[a-z]/>)
519and in the C<tr///> (also known as C<y///>) operator are not magically
58c274a1 520Unicode-aware. What this means that C<[A-Za-z]> will not magically start
ba62762e
JH
521to mean "all alphabetic letters" (not that it does mean that even for
5228-bit characters, you should be using C</[[:alpha]]/> for that).
523
58c274a1
JF
524For specifying things like that in regular expressions, you can use the
525various Unicode properties, C<\pL> or perhaps C<\p{Alphabetic}>, in this particular case. You can
ba62762e
JH
526use Unicode code points as the end points of character ranges, but
527that means that particular code point range, nothing more. For
528further information, see L<perlunicode>.
529
530=item *
531
532String-To-Number Conversions
533
534Unicode does define several other decimal (and numeric) characters
535than just the familiar 0 to 9, such as the Arabic and Indic digits.
536Perl does not support string-to-number conversion for digits other
58c274a1 537than ASCII 0 to 9 (and ASCII a to f for hexadecimal).
ba62762e
JH
538
539=back
540
541=head2 Questions With Answers
542
543=over 4
544
545=item Will My Old Scripts Break?
546
547Very probably not. Unless you are generating Unicode characters
548somehow, any old behaviour should be preserved. About the only
549behaviour that has changed and which could start generating Unicode
550is the old behaviour of C<chr()> where supplying an argument more
551than 255 produced a character modulo 255 (for example, C<chr(300)>
552was equal to C<chr(45)>).
553
554=item How Do I Make My Scripts Work With Unicode?
555
556Very little work should be needed since nothing changes until you
557somehow generate Unicode data. The greatest trick will be getting
558input as Unicode, and for that see the earlier I/O discussion.
559
560=item How Do I Know Whether My String Is In Unicode?
561
8baee566
JF
562 @@| Note to P5P -- I see two problems with this section. One is
563 @@| that Encode::is_utf8() really should be named
564 @@| Encode::is_Unicode(), since that's what it's telling you,
565 @@| isn't it? This
566 @@| Encode::is_utf8(pack("U"), 0xDF)
567 @@| returns true, even though the string being checked is
568 @@| internally kept in the native 8-bit encoding, but flagged as
569 @@| Unicode.
570 @@|
571 @@| Another problem is that yeah, I can see situations where
572 @@| someone wants to know if a string is Unicode, or if it's
573 @@| still in the native 8-bit encoding. What's wrong with that?
574 @@| Perhaps when this section was added, it was with the that
575 @@| that users don't need to care the particular encoding used
576 @@| internally, and that's still the case (except for efficiency
577 @@| issues -- reading utf8 is likely much faster than reading,
578 @@| say, Shift-JIS).
579 @@|
580 @@| Can is_utf8 be renamed to is_Unicode()?
581
ba62762e
JH
582You shouldn't care. No, you really shouldn't. If you have
583to care (beyond the cases described above), it means that we
584didn't get the transparency of Unicode quite right.
585
586Okay, if you insist:
587
588 use Encode 'is_utf8';
589 print is_utf8($string) ? 1 : 0, "\n";
590
591But note that this doesn't mean that any of the characters in the
592string are necessary UTF-8 encoded, or that any of the characters have
593code points greater than 0xFF (255) or even 0x80 (128), or that the
594string has any characters at all. All the C<is_utf8()> does is to
595return the value of the internal "utf8ness" flag attached to the
596$string. If the flag is on, characters added to that string will be
597automatically upgraded to UTF-8 (and even then only if they really
598need to be upgraded, that is, if their code point is greater than 0xFF).
599
600Sometimes you might really need to know the byte length of a string
601instead of the character length. For that use the C<bytes> pragma
602and its only defined function C<length()>:
603
604 my $unicode = chr(0x100);
605 print length($unicode), "\n"; # will print 1
606 use bytes;
607 print length($unicode), "\n"; # will print 2 (the 0xC4 0x80 of the UTF-8)
608
8baee566 609=item How Do I Detect Data That's Not Valid In a Particular Encoding
ba62762e 610
8baee566
JF
611Use the C<Encode> package to try converting it.
612For example,
ba62762e
JH
613
614 use Encode 'encode_utf8';
8baee566 615 if (encode_utf8($string_of_bytes_that_I_think_is_utf8)) {
ba62762e
JH
616 # valid
617 } else {
618 # invalid
619 }
620
8baee566 621For UTF-8 only, you can use:
ba62762e
JH
622
623 use warnings;
8baee566 624 @chars = unpack("U0U*", $string_of_bytes_that_I_think_is_utf8);
ba62762e 625
8baee566
JF
626If invalid, a C<Malformed UTF-8 character (byte 0x##) in
627unpack> is produced. The "U0" means "expect strictly UTF-8
628encoded Unicode". Without that the C<unpack("U*", ...)>
629would accept also data like C<chr(0xFF>).
ba62762e 630
8baee566 631=item How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa?
ba62762e 632
8baee566
JF
633This probably isn't as useful as you might think.
634Normally, you shouldn't need to.
ba62762e 635
8baee566
JF
636In one sense, what you are asking doesn't make much sense: Encodings are
637for characters, and binary data is not "characters", so converting "data"
638into some encoding isn't meaningful unless you know in what character set
639and encoding the binary data is in, in which case it's not binary data, now
640is it?
641
642If you have a raw sequence of bytes that you know should be interpreted via
643a particular encoding, you can use C<Encode>:
ba62762e
JH
644
645 use Encode 'from_to';
646 from_to($data, "iso-8859-1", "utf-8"); # from latin-1 to utf-8
647
8baee566
JF
648The call to from_to() changes the bytes in $data, but nothing material
649about the nature of the string has changed as far as Perl is concerned.
650Both before and after the call, the string $data contains just a bunch of
6518-bit bytes. As far as Perl is concerned, the encoding of the string (as
652Perl sees it) remains as "system-native 8-bit bytes".
653
654You might relate this to a fictional 'Translate' module:
655
656 use Translate;
657 my $phrase = "Yes";
658 Translate::from_to($phrase, 'english', 'deutsch');
659 ## phrase now contains "Ja"
ba62762e 660
8baee566
JF
661The contents of the string changes, but not the nature of the string.
662Perl doesn't know any more after the call than before that the contents
663of the string indicates the affirmative.
ba62762e 664
8baee566
JF
665Back to converting data, if you have (or want) data in your system's native
6668-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use pack/unpack to
667convert to/from Unicode.
ba62762e 668
8baee566
JF
669 $native_string = pack("C*", unpack("U*", $Unicode_string));
670 $Unicode_string = pack("U*", unpack("C*", $native_string));
ba62762e
JH
671
672If you have a sequence of bytes you B<know> is valid UTF-8,
673but Perl doesn't know it yet, you can make Perl a believer, too:
674
675 use Encode 'decode_utf8';
8baee566 676 $Unicode = decode_utf8($bytes);
ba62762e
JH
677
678You can convert well-formed UTF-8 to a sequence of bytes, but if
679you just want to convert random binary data into UTF-8, you can't.
680Any random collection of bytes isn't well-formed UTF-8. You can
681use C<unpack("C*", $string)> for the former, and you can create
8baee566 682well-formed Unicode data by C<pack("U*", 0xff, ...)>.
ba62762e
JH
683
684=item How Do I Display Unicode? How Do I Input Unicode?
685
686See http://www.hclrss.demon.co.uk/unicode/ and
687http://www.cl.cam.ac.uk/~mgk25/unicode.html
688
689=item How Does Unicode Work With Traditional Locales?
690
691In Perl, not very well. Avoid using locales through the C<locale>
692pragma. Use only one or the other.
693
694=back
695
696=head2 Hexadecimal Notation
697
698The Unicode standard prefers using hexadecimal notation because that
699shows better the division of Unicode into blocks of 256 characters.
700Hexadecimal is also simply shorter than decimal. You can use decimal
701notation, too, but learning to use hexadecimal just makes life easier
702with the Unicode standard.
703
704The C<0x> prefix means a hexadecimal number, the digits are 0-9 I<and>
705a-f (or A-F, case doesn't matter). Each hexadecimal digit represents
706four bits, or half a byte. C<print 0x..., "\n"> will show a
707hexadecimal number in decimal, and C<printf "%x\n", $decimal> will
708show a decimal number in hexadecimal. If you have just the
709"hexdigits" of a hexadecimal number, you can use the C<hex()>
710function.
711
712 print 0x0009, "\n"; # 9
713 print 0x000a, "\n"; # 10
714 print 0x000f, "\n"; # 15
715 print 0x0010, "\n"; # 16
716 print 0x0011, "\n"; # 17
717 print 0x0100, "\n"; # 256
718
719 print 0x0041, "\n"; # 65
720
721 printf "%x\n", 65; # 41
722 printf "%#x\n", 65; # 0x41
723
724 print hex("41"), "\n"; # 65
725
726=head2 Further Resources
727
728=over 4
729
730=item *
731
732Unicode Consortium
733
734 http://www.unicode.org/
735
736=item *
737
738Unicode FAQ
739
740 http://www.unicode.org/unicode/faq/
741
742=item *
743
744Unicode Glossary
745
746 http://www.unicode.org/glossary/
747
748=item *
749
750Unicode Useful Resources
751
752 http://www.unicode.org/unicode/onlinedat/resources.html
753
754=item *
755
756Unicode and Multilingual Support in HTML, Fonts, Web Browsers and Other Applications
757
758 http://www.hclrss.demon.co.uk/unicode/
759
760=item *
761
762UTF-8 and Unicode FAQ for Unix/Linux
763
764 http://www.cl.cam.ac.uk/~mgk25/unicode.html
765
766=item *
767
768Legacy Character Sets
769
770 http://www.czyborra.com/
771 http://www.eki.ee/letter/
772
773=item *
774
775The Unicode support files live within the Perl installation in the
776directory
777
778 $Config{installprivlib}/unicore
779
780in Perl 5.8.0 or newer, and
781
782 $Config{installprivlib}/unicode
783
784in the Perl 5.6 series. (The renaming to F<lib/unicore> was done to
785avoid naming conflicts with lib/Unicode in case-insensitive filesystems.)
786The main Unicode data file is F<Unicode.txt> (or F<Unicode.301> in
787Perl 5.6.1.) You can find the C<$Config{installprivlib}> by
788
789 perl "-V:installprivlib"
790
791Note that some of the files have been renamed from the Unicode
792standard since the Perl installation tries to live by the "8.3"
793filenaming restrictions. The renamings are shown in the
794accompanying F<rename> file.
795
796You can explore various information from the Unicode data files using
797the C<Unicode::UCD> module.
798
799=back
800
f6edf83b
JH
801=head1 UNICODE IN OLDER PERLS
802
803If you cannot upgrade your Perl to 5.8.0 or later, you can still
804do some Unicode processing by using the modules C<Unicode::String>,
805C<Unicode::Map8>, and C<Unicode::Map>, available from CPAN.
806If you have the GNU recode installed, you can also use the
807Perl frontend C<Convert::Recode> for character conversions.
808
ba62762e
JH
809=head1 SEE ALSO
810
811L<perlunicode>, L<Encode>, L<encoding>, L<open>, L<utf8>, L<bytes>,
812L<perlretut>, L<Unicode::Collate>, L<Unicode::Normalize>, L<Unicode::UCD>
813
814=head1 ACKNOWLEDGEMENTS
815
816Thanks to the kind readers of the perl5-porters@perl.org,
817perl-unicode@perl.org, linux-utf8@nl.linux.org, and unicore@unicode.org
818mailing lists for their valuable feedback.
819
820=head1 AUTHOR, COPYRIGHT, AND LICENSE
821
822Copyright 2001 Jarkko Hietaniemi <jhi@iki.fi>
823
824This document may be distributed under the same terms as Perl itself.