beb742efb1a5cd2fde9bca0e1363b50245281294
[p5sagit/p5-mst-13.2.git] / pod / perlunicode.pod
1 =head1 NAME
2
3 perlunicode - Unicode support in Perl
4
5 =head1 DESCRIPTION
6
7 =head2 Important Caveats
8
9 Unicode support is an extensive requirement. While perl does not
10 implement the Unicode standard or the accompanying technical reports
11 from cover to cover, Perl does support many Unicode features.
12
13 =over 4
14
15 =item Input and Output Disciplines
16
17 A filehandle can be marked as containing perl's internal Unicode
18 encoding (UTF-8 or UTF-EBCDIC) by opening it with the ":utf8" layer.
19 Other encodings can be converted to perl's encoding on input, or from
20 perl's encoding on output by use of the ":encoding(...)" layer.
21 See L<open>.
22
23 To mark the Perl source itself as being in a particular encoding,
24 see L<encoding>.
25
26 =item Regular Expressions
27
28 The regular expression compiler produces polymorphic opcodes.  That is,
29 the pattern adapts to the data and automatically switch to the Unicode
30 character scheme when presented with Unicode data, or a traditional
31 byte scheme when presented with byte data.
32
33 =item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts
34
35 As a compatibility measure, this pragma must be explicitly used to
36 enable recognition of UTF-8 in the Perl scripts themselves on ASCII
37 based machines, or to recognize UTF-EBCDIC on EBCDIC based machines.
38 B<NOTE: this should be the only place where an explicit C<use utf8>
39 is needed>.
40
41 You can also use the C<encoding> pragma to change the default encoding
42 of the data in your script; see L<encoding>.
43
44 =back
45
46 =head2 Byte and Character semantics
47
48 Beginning with version 5.6, Perl uses logically wide characters to
49 represent strings internally.
50
51 In future, Perl-level operations can be expected to work with
52 characters rather than bytes, in general.
53
54 However, as strictly an interim compatibility measure, Perl aims to
55 provide a safe migration path from byte semantics to character
56 semantics for programs.  For operations where Perl can unambiguously
57 decide that the input data is characters, Perl now switches to
58 character semantics.  For operations where this determination cannot
59 be made without additional information from the user, Perl decides in
60 favor of compatibility, and chooses to use byte semantics.
61
62 This behavior preserves compatibility with earlier versions of Perl,
63 which allowed byte semantics in Perl operations, but only as long as
64 none of the program's inputs are marked as being as source of Unicode
65 character data.  Such data may come from filehandles, from calls to
66 external programs, from information provided by the system (such as %ENV),
67 or from literals and constants in the source text.
68
69 On Windows platforms, if the C<-C> command line switch is used, (or the
70 ${^WIDE_SYSTEM_CALLS} global flag is set to C<1>), all system calls
71 will use the corresponding wide character APIs.  Note that this is
72 currently only implemented on Windows since other platforms lack an
73 API standard on this area.
74
75 Regardless of the above, the C<bytes> pragma can always be used to
76 force byte semantics in a particular lexical scope.  See L<bytes>.
77
78 The C<utf8> pragma is primarily a compatibility device that enables
79 recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
80 Note that this pragma is only required until a future version of Perl
81 in which character semantics will become the default.  This pragma may
82 then become a no-op.  See L<utf8>.
83
84 Unless mentioned otherwise, Perl operators will use character semantics
85 when they are dealing with Unicode data, and byte semantics otherwise.
86 Thus, character semantics for these operations apply transparently; if
87 the input data came from a Unicode source (for example, by adding a
88 character encoding discipline to the filehandle whence it came, or a
89 literal Unicode string constant in the program), character semantics
90 apply; otherwise, byte semantics are in effect.  To force byte semantics
91 on Unicode data, the C<bytes> pragma should be used.
92
93 Notice that if you concatenate strings with byte semantics and strings
94 with Unicode character data, the bytes will by default be upgraded
95 I<as if they were ISO 8859-1 (Latin-1)> (or if in EBCDIC, after a
96 translation to ISO 8859-1). This is done without regard to the
97 system's native 8-bit encoding, so to change this for systems with
98 non-Latin-1 (or non-EBCDIC) native encodings, use the C<encoding>
99 pragma, see L<encoding>.
100
101 Under character semantics, many operations that formerly operated on
102 bytes change to operating on characters. A character in Perl is
103 logically just a number ranging from 0 to 2**31 or so. Larger
104 characters may encode to longer sequences of bytes internally, but
105 this is just an internal detail which is hidden at the Perl level.
106 See L<perluniintro> for more on this.
107
108 =head2 Effects of character semantics
109
110 Character semantics have the following effects:
111
112 =over 4
113
114 =item *
115
116 Strings and patterns may contain characters that have an ordinal value
117 larger than 255.
118
119 If you use a Unicode editor to edit your program, Unicode characters
120 may occur directly within the literal strings in one of the various
121 Unicode encodings (UTF-8, UTF-EBCDIC, UCS-2, etc.), but are recognized
122 as such (and converted to Perl's internal representation) only if the
123 appropriate L<encoding> is specified.
124
125 You can also get Unicode characters into a string by using the C<\x{...}>
126 notation, putting the Unicode code for the desired character, in
127 hexadecimal, into the curlies. For instance, a smiley face is C<\x{263A}>.
128 This works only for characters with a code 0x100 and above.
129
130 Additionally, if you
131    use charnames ':full';
132 you can use the C<\N{...}> notation, putting the official Unicode character
133 name within the curlies. For example, C<\N{WHITE SMILING FACE}>.
134 This works for all characters that have names.
135
136 =item *
137
138 If an appropriate L<encoding> is specified,
139 identifiers within the Perl script may contain Unicode alphanumeric
140 characters, including ideographs.  (You are currently on your own when
141 it comes to using the canonical forms of characters--Perl doesn't
142 (yet) attempt to canonicalize variable names for you.)
143
144 =item *
145
146 Regular expressions match characters instead of bytes.  For instance,
147 "." matches a character instead of a byte.  (However, the C<\C> pattern
148 is provided to force a match a single byte ("C<char>" in C, hence C<\C>).)
149
150 =item *
151
152 Character classes in regular expressions match characters instead of
153 bytes, and match against the character properties specified in the
154 Unicode properties database.  So C<\w> can be used to match an
155 ideograph, for instance.
156
157 =item *
158
159 Named Unicode properties and block ranges may be used as character
160 classes via the new C<\p{}> (matches property) and C<\P{}> (doesn't
161 match property) constructs.  For instance, C<\p{Lu}> matches any
162 character with the Unicode "Lu" (Letter, uppercase) property, while
163 C<\p{M}> matches any character with a "M" (mark -- accents and such)
164 property.  Single letter properties may omit the brackets, so that can
165 be written C<\pM> also.  Many predefined character classes are
166 available, such as C<\p{IsMirrored}> and C<\p{InTibetan}>.
167
168 The C<\p{Is...}> test for "general properties" such as "letter",
169 "digit", while the C<\p{In...}> test for Unicode scripts and blocks.
170
171 The official Unicode script and block names have spaces and dashes as
172 separators, but for convenience you can have dashes, spaces, and
173 underbars at every word division, and you need not care about correct
174 casing.  It is recommended, however, that for consistency you use the
175 following naming: the official Unicode script, block, or property name
176 (see below for the additional rules that apply to block names), with
177 whitespace and dashes replaced with underbar, and the words
178 "uppercase-first-lowercase-rest".  That is, "Latin-1 Supplement"
179 becomes "Latin_1_Supplement".
180
181 You can also negate both C<\p{}> and C<\P{}> by introducing a caret
182 (^) between the first curly and the property name: C<\p{^In_Tamil}> is
183 equal to C<\P{In_Tamil}>.
184
185 The C<In> and C<Is> can be left out: C<\p{Greek}> is equal to
186 C<\p{In_Greek}>, C<\P{Pd}> is equal to C<\P{Pd}>.
187
188     Short       Long
189
190     L           Letter
191     Lu          Uppercase_Letter
192     Ll          Lowercase_Letter
193     Lt          Titlecase_Letter
194     Lm          Modifier_Letter
195     Lo          Other_Letter
196
197     M           Mark
198     Mn          Nonspacing_Mark
199     Mc          Spacing_Mark
200     Me          Enclosing_Mark
201
202     N           Number
203     Nd          Decimal_Number
204     Nl          Letter_Number
205     No          Other_Number
206
207     P           Punctuation
208     Pc          Connector_Punctuation
209     Pd          Dash_Punctuation
210     Ps          Open_Punctuation
211     Pe          Close_Punctuation
212     Pi          Initial_Punctuation
213                 (may behave like Ps or Pe depending on usage)
214     Pf          Final_Punctuation
215                 (may behave like Ps or Pe depending on usage)
216     Po          Other_Punctuation
217
218     S           Symbol
219     Sm          Math_Symbol
220     Sc          Currency_Symbol
221     Sk          Modifier_Symbol
222     So          Other_Symbol
223
224     Z           Separator
225     Zs          Space_Separator
226     Zl          Line_Separator
227     Zp          Paragraph_Separator
228
229     C           Other
230     Cc          Control
231     Cf          Format
232     Cs          Surrogate
233     Co          Private_Use
234     Cn          Unassigned
235
236 The single-letter properties match all characters in any of the
237 two-letter sub-properties starting with the same letter.
238 There's also C<L&> which is an alias for C<Ll>, C<Lu>, and C<Lt>.
239
240 The following reserved ranges have C<In> tests:
241
242     CJK_Ideograph_Extension_A
243     CJK_Ideograph
244     Hangul_Syllable
245     Non_Private_Use_High_Surrogate
246     Private_Use_High_Surrogate
247     Low_Surrogate
248     Private_Surrogate
249     CJK_Ideograph_Extension_B
250     Plane_15_Private_Use
251     Plane_16_Private_Use
252
253 For example C<"\x{AC00}" =~ \p{HangulSyllable}> will test true.
254 (Handling of surrogates is not implemented yet, because Perl
255 uses UTF-8 and not UTF-16 internally to represent Unicode.
256 So you really can't use the "Cs" category.)
257
258 Additionally, because scripts differ in their directionality
259 (for example Hebrew is written right to left), all characters
260 have their directionality defined:
261
262     BidiL       Left-to-Right
263     BidiLRE     Left-to-Right Embedding
264     BidiLRO     Left-to-Right Override
265     BidiR       Right-to-Left
266     BidiAL      Right-to-Left Arabic
267     BidiRLE     Right-to-Left Embedding
268     BidiRLO     Right-to-Left Override
269     BidiPDF     Pop Directional Format
270     BidiEN      European Number
271     BidiES      European Number Separator
272     BidiET      European Number Terminator
273     BidiAN      Arabic Number
274     BidiCS      Common Number Separator
275     BidiNSM     Non-Spacing Mark
276     BidiBN      Boundary Neutral
277     BidiB       Paragraph Separator
278     BidiS       Segment Separator
279     BidiWS      Whitespace
280     BidiON      Other Neutrals
281
282 =back
283
284 =head2 Scripts
285
286 The scripts available for C<\p{In...}> and C<\P{In...}>, for example
287 C<\p{InLatin}> or \p{InCyrillic>, are as follows:
288
289     Arabic
290     Armenian
291     Bengali
292     Bopomofo
293     Canadian-Aboriginal
294     Cherokee
295     Cyrillic
296     Deseret
297     Devanagari
298     Ethiopic
299     Georgian
300     Gothic
301     Greek
302     Gujarati
303     Gurmukhi
304     Han
305     Hangul
306     Hebrew
307     Hiragana
308     Inherited
309     Kannada
310     Katakana
311     Khmer
312     Lao
313     Latin
314     Malayalam
315     Mongolian
316     Myanmar
317     Ogham
318     Old-Italic
319     Oriya
320     Runic
321     Sinhala
322     Syriac
323     Tamil
324     Telugu
325     Thaana
326     Thai
327     Tibetan
328     Yi
329
330 There are also extended property classes that supplement the basic
331 properties, defined by the F<PropList> Unicode database:
332
333     ASCII_Hex_Digit
334     Bidi_Control
335     Dash
336     Diacritic
337     Extender
338     Hex_Digit
339     Hyphen
340     Ideographic
341     Join_Control
342     Noncharacter_Code_Point
343     Other_Alphabetic
344     Other_Lowercase
345     Other_Math
346     Other_Uppercase
347     Quotation_Mark
348     White_Space
349
350 and further derived properties:
351
352     Alphabetic      Lu + Ll + Lt + Lm + Lo + Other_Alphabetic
353     Lowercase       Ll + Other_Lowercase
354     Uppercase       Lu + Other_Uppercase
355     Math            Sm + Other_Math
356
357     ID_Start        Lu + Ll + Lt + Lm + Lo + Nl
358     ID_Continue     ID_Start + Mn + Mc + Nd + Pc
359
360     Any             Any character
361     Assigned        Any non-Cn character
362     Common          Any character (or unassigned code point)
363                     not explicitly assigned to a script
364
365 =head2 Blocks
366
367 In addition to B<scripts>, Unicode also defines B<blocks> of
368 characters.  The difference between scripts and blocks is that the
369 scripts concept is closer to natural languages, while the blocks
370 concept is more an artificial grouping based on groups of 256 Unicode
371 characters.  For example, the C<Latin> script contains letters from
372 many blocks.  On the other hand, the C<Latin> script does not contain
373 all the characters from those blocks. It does not, for example,
374 contain digits because digits are shared across many scripts.  Digits
375 and other similar groups, like punctuation, are in a category called
376 C<Common>.
377
378 For more about scripts, see the UTR #24:
379
380    http://www.unicode.org/unicode/reports/tr24/
381
382 For more about blocks, see:
383
384    http://www.unicode.org/Public/UNIDATA/Blocks.txt
385
386 Because there are overlaps in naming (there are, for example, both
387 a script called C<Katakana> and a block called C<Katakana>, the block
388 version has C<Block> appended to its name, C<\p{InKatakanaBlock}>.
389
390 Notice that this definition was introduced in Perl 5.8.0: in Perl
391 5.6 only the blocks were used; in Perl 5.8.0 scripts became the
392 preferential Unicode character class definition (prompted by
393 recommendations from the Unicode consortium); this meant that
394 the definitions of some character classes changed (the ones in
395 the below list that have the C<Block> appended).
396
397    Alphabetic Presentation Forms
398    Arabic Block
399    Arabic Presentation Forms-A
400    Arabic Presentation Forms-B
401    Armenian Block
402    Arrows
403    Basic Latin
404    Bengali Block
405    Block Elements
406    Bopomofo Block
407    Bopomofo Extended
408    Box Drawing
409    Braille Patterns
410    Byzantine Musical Symbols
411    CJK Compatibility
412    CJK Compatibility Forms
413    CJK Compatibility Ideographs
414    CJK Compatibility Ideographs Supplement
415    CJK Radicals Supplement
416    CJK Symbols and Punctuation
417    CJK Unified Ideographs
418    CJK Unified Ideographs Extension A
419    CJK Unified Ideographs Extension B
420    Cherokee Block
421    Combining Diacritical Marks
422    Combining Half Marks
423    Combining Marks for Symbols
424    Control Pictures
425    Currency Symbols
426    Cyrillic Block
427    Deseret Block
428    Devanagari Block
429    Dingbats
430    Enclosed Alphanumerics
431    Enclosed CJK Letters and Months
432    Ethiopic Block
433    General Punctuation
434    Geometric Shapes
435    Georgian Block
436    Gothic Block
437    Greek Block
438    Greek Extended
439    Gujarati Block
440    Gurmukhi Block
441    Halfwidth and Fullwidth Forms
442    Hangul Compatibility Jamo
443    Hangul Jamo
444    Hangul Syllables
445    Hebrew Block
446    High Private Use Surrogates
447    High Surrogates
448    Hiragana Block
449    IPA Extensions
450    Ideographic Description Characters
451    Kanbun
452    Kangxi Radicals
453    Kannada Block
454    Katakana Block
455    Khmer Block
456    Lao Block
457    Latin 1 Supplement
458    Latin Extended Additional
459    Latin Extended-A
460    Latin Extended-B
461    Letterlike Symbols
462    Low Surrogates
463    Malayalam Block
464    Mathematical Alphanumeric Symbols
465    Mathematical Operators
466    Miscellaneous Symbols
467    Miscellaneous Technical
468    Mongolian Block
469    Musical Symbols
470    Myanmar Block
471    Number Forms
472    Ogham Block
473    Old Italic Block
474    Optical Character Recognition
475    Oriya Block
476    Private Use
477    Runic Block
478    Sinhala Block
479    Small Form Variants
480    Spacing Modifier Letters
481    Specials
482    Superscripts and Subscripts
483    Syriac Block
484    Tags
485    Tamil Block
486    Telugu Block
487    Thaana Block
488    Thai Block
489    Tibetan Block
490    Unified Canadian Aboriginal Syllabics
491    Yi Radicals
492    Yi Syllables
493
494 =over 4
495
496 =item *
497
498 The special pattern C<\X> match matches any extended Unicode sequence
499 (a "combining character sequence" in Standardese), where the first
500 character is a base character and subsequent characters are mark
501 characters that apply to the base character.  It is equivalent to
502 C<(?:\PM\pM*)>.
503
504 =item *
505
506 The C<tr///> operator translates characters instead of bytes.  Note
507 that the C<tr///CU> functionality has been removed, as the interface
508 was a mistake.  For similar functionality see pack('U0', ...) and
509 pack('C0', ...).
510
511 =item *
512
513 Case translation operators use the Unicode case translation tables
514 when provided character input.  Note that C<uc()> (also known as C<\U>
515 in doublequoted strings) translates to uppercase, while C<ucfirst>
516 (also known as C<\u> in doublequoted strings) translates to titlecase
517 (for languages that make the distinction).  Naturally the
518 corresponding backslash sequences have the same semantics.
519
520 =item *
521
522 Most operators that deal with positions or lengths in the string will
523 automatically switch to using character positions, including
524 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
525 C<sprintf()>, C<write()>, and C<length()>.  Operators that
526 specifically don't switch include C<vec()>, C<pack()>, and
527 C<unpack()>.  Operators that really don't care include C<chomp()>, as
528 well as any other operator that treats a string as a bucket of bits,
529 such as C<sort()>, and the operators dealing with filenames.
530
531 =item *
532
533 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
534 since they're often used for byte-oriented formats.  (Again, think
535 "C<char>" in the C language.)  However, there is a new "C<U>" specifier
536 that will convert between Unicode characters and integers.
537
538 =item *
539
540 The C<chr()> and C<ord()> functions work on characters.  This is like
541 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
542 C<unpack("C")>.  In fact, the latter are how you now emulate
543 byte-oriented C<chr()> and C<ord()> for Unicode strings.
544 (Note that this reveals the internal encoding of Unicode strings,
545 which is not something one normally needs to care about at all.)
546
547 =item *
548
549 The bit string operators C<& | ^ ~> can operate on character data.
550 However, for backward compatibility reasons (bit string operations
551 when the characters all are less than 256 in ordinal value) one should
552 not mix C<~> (the bit complement) and characters both less than 256 and
553 equal or greater than 256.  Most importantly, the DeMorgan's laws
554 (C<~($x|$y) eq ~$x&~$y>, C<~($x&$y) eq ~$x|~$y>) won't hold.
555 Another way to look at this is that the complement cannot return
556 B<both> the 8-bit (byte) wide bit complement B<and> the full character
557 wide bit complement.
558
559 =item *
560
561 lc(), uc(), lcfirst(), and ucfirst() work for the following cases:
562
563 =over 8
564
565 =item *
566
567 the case mapping is from a single Unicode character to another
568 single Unicode character
569
570 =item *
571
572 the case mapping is from a single Unicode character to more
573 than one Unicode character
574
575 =back
576
577 What doesn't yet work are the following cases:
578
579 =over 8
580
581 =item *
582
583 the "final sigma" (Greek)
584
585 =item *
586
587 anything to with locales (Lithuanian, Turkish, Azeri)
588
589 =back
590
591 See the Unicode Technical Report #21, Case Mappings, for more details.
592
593 =item *
594
595 And finally, C<scalar reverse()> reverses by character rather than by byte.
596
597 =back
598
599 =head2 Character encodings for input and output
600
601 See L<Encode>.
602
603 =head1 CAVEATS
604
605 Whether an arbitrary piece of data will be treated as "characters" or
606 "bytes" by internal operations cannot be divined at the current time.
607
608 Use of locales with Unicode data may lead to odd results.  Currently
609 there is some attempt to apply 8-bit locale info to characters in the
610 range 0..255, but this is demonstrably incorrect for locales that use
611 characters above that range when mapped into Unicode.  It will also
612 tend to run slower.  Avoidance of locales is strongly encouraged.
613
614 =head1 UNICODE REGULAR EXPRESSION SUPPORT LEVEL
615
616 The following list of Unicode regular expression support describes
617 feature by feature the Unicode support implemented in Perl as of Perl
618 5.8.0.  The "Level N" and the section numbers refer to the Unicode
619 Technical Report 18, "Unicode Regular Expression Guidelines".
620
621 =over 4
622
623 =item *
624
625 Level 1 - Basic Unicode Support
626
627         2.1 Hex Notation                        - done          [1]
628             Named Notation                      - done          [2]
629         2.2 Categories                          - done          [3][4]
630         2.3 Subtraction                         - MISSING       [5][6]
631         2.4 Simple Word Boundaries              - done          [7]
632         2.5 Simple Loose Matches                - done          [8]
633         2.6 End of Line                         - MISSING       [9][10]
634
635         [ 1] \x{...}
636         [ 2] \N{...}
637         [ 3] . \p{Is...} \P{Is...}
638         [ 4] now scripts (see UTR#24 Script Names) in addition to blocks
639         [ 5] have negation
640         [ 6] can use look-ahead to emulate subtraction (*)
641         [ 7] include Letters in word characters
642         [ 8] note that perl does Full casefolding in matching, not Simple:
643              for example U+1F88 is equivalent with U+1F000 U+03B9,
644              not with 1F80.  This difference matters for certain Greek
645              capital letters with certain modifiers: the Full casefolding
646              decomposes the letter, while the Simple casefolding would map
647              it to a single character.
648         [ 9] see UTR#13 Unicode Newline Guidelines
649         [10] should do ^ and $ also on \x{85}, \x{2028} and \x{2029})
650              (should also affect <>, $., and script line numbers)
651              (the \x{85}, \x{2028} and \x{2029} do match \s)
652
653 (*) You can mimic class subtraction using lookahead.
654 For example, what TR18 might write as
655
656     [{Greek}-[{UNASSIGNED}]]
657
658 in Perl can be written as:
659
660     (?!\p{UNASSIGNED})\p{GreekBlock}
661     (?=\p{ASSIGNED})\p{GreekBlock}
662
663 But in this particular example, you probably really want
664
665     \p{Greek}
666
667 which will match assigned characters known to be part of the Greek script.
668
669 =item *
670
671 Level 2 - Extended Unicode Support
672
673         3.1 Surrogates                          - MISSING
674         3.2 Canonical Equivalents               - MISSING       [11][12]
675         3.3 Locale-Independent Graphemes        - MISSING       [13]
676         3.4 Locale-Independent Words            - MISSING       [14]
677         3.5 Locale-Independent Loose Matches    - MISSING       [15]
678
679         [11] see UTR#15 Unicode Normalization
680         [12] have Unicode::Normalize but not integrated to regexes
681         [13] have \X but at this level . should equal that
682         [14] need three classes, not just \w and \W
683         [15] see UTR#21 Case Mappings
684
685 =item *
686
687 Level 3 - Locale-Sensitive Support
688
689         4.1 Locale-Dependent Categories         - MISSING
690         4.2 Locale-Dependent Graphemes          - MISSING       [16][17]
691         4.3 Locale-Dependent Words              - MISSING
692         4.4 Locale-Dependent Loose Matches      - MISSING
693         4.5 Locale-Dependent Ranges             - MISSING
694
695         [16] see UTR#10 Unicode Collation Algorithms
696         [17] have Unicode::Collate but not integrated to regexes
697
698 =back
699
700 =head2 Unicode Encodings
701
702 Unicode characters are assigned to I<code points> which are abstract
703 numbers.  To use these numbers various encodings are needed.
704
705 =over 4
706
707 =item UTF-8
708
709 UTF-8 is a variable-length (1 to 6 bytes, current character allocations
710 require 4 bytes), byteorder independent encoding. For ASCII, UTF-8 is
711 transparent (and we really do mean 7-bit ASCII, not another 8-bit encoding).
712
713 The following table is from Unicode 3.1.
714
715  Code Points            1st Byte  2nd Byte  3rd Byte  4th Byte
716
717    U+0000..U+007F       00..7F   
718    U+0080..U+07FF       C2..DF    80..BF   
719    U+0800..U+0FFF       E0        A0..BF    80..BF  
720    U+1000..U+FFFF       E1..EF    80..BF    80..BF  
721   U+10000..U+3FFFF      F0        90..BF    80..BF    80..BF
722   U+40000..U+FFFFF      F1..F3    80..BF    80..BF    80..BF
723  U+100000..U+10FFFF     F4        80..8F    80..BF    80..BF
724
725 Or, another way to look at it, as bits:
726
727  Code Points                    1st Byte   2nd Byte  3rd Byte  4th Byte
728
729                     0aaaaaaa     0aaaaaaa
730             00000bbbbbaaaaaa     110bbbbb  10aaaaaa
731             ccccbbbbbbaaaaaa     1110cccc  10bbbbbb  10aaaaaa
732   00000dddccccccbbbbbbaaaaaa     11110ddd  10cccccc  10bbbbbb  10aaaaaa
733
734 As you can see, the continuation bytes all begin with C<10>, and the
735 leading bits of the start byte tells how many bytes the are in the
736 encoded character.
737
738 =item UTF-EBCDIC
739
740 Like UTF-8, but EBCDIC-safe, as UTF-8 is ASCII-safe.
741
742 =item UTF-16, UTF-16BE, UTF16-LE, Surrogates, and BOMs (Byte Order Marks)
743
744 (The followings items are mostly for reference, Perl doesn't
745 use them internally.)
746
747 UTF-16 is a 2 or 4 byte encoding.  The Unicode code points
748 0x0000..0xFFFF are stored in two 16-bit units, and the code points
749 0x010000..0x10FFFF in two 16-bit units.  The latter case is
750 using I<surrogates>, the first 16-bit unit being the I<high
751 surrogate>, and the second being the I<low surrogate>.
752
753 Surrogates are code points set aside to encode the 0x01000..0x10FFFF
754 range of Unicode code points in pairs of 16-bit units.  The I<high
755 surrogates> are the range 0xD800..0xDBFF, and the I<low surrogates>
756 are the range 0xDC00..0xDFFFF.  The surrogate encoding is
757
758         $hi = ($uni - 0x10000) / 0x400 + 0xD800;
759         $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
760
761 and the decoding is
762
763         $uni = 0x10000 + ($hi - 0xD8000) * 0x400 + ($lo - 0xDC00);
764
765 If you try to generate surrogates (for example by using chr()), you
766 will get a warning if warnings are turned on (C<-w> or C<use
767 warnings;>) because those code points are not valid for a Unicode
768 character.
769
770 Because of the 16-bitness, UTF-16 is byteorder dependent.  UTF-16
771 itself can be used for in-memory computations, but if storage or
772 transfer is required, either UTF-16BE (Big Endian) or UTF-16LE
773 (Little Endian) must be chosen.
774
775 This introduces another problem: what if you just know that your data
776 is UTF-16, but you don't know which endianness?  Byte Order Marks
777 (BOMs) are a solution to this.  A special character has been reserved
778 in Unicode to function as a byte order marker: the character with the
779 code point 0xFEFF is the BOM.
780
781 The trick is that if you read a BOM, you will know the byte order,
782 since if it was written on a big endian platform, you will read the
783 bytes 0xFE 0xFF, but if it was written on a little endian platform,
784 you will read the bytes 0xFF 0xFE.  (And if the originating platform
785 was writing in UTF-8, you will read the bytes 0xEF 0xBB 0xBF.)
786
787 The way this trick works is that the character with the code point
788 0xFFFE is guaranteed not to be a valid Unicode character, so the
789 sequence of bytes 0xFF 0xFE is unambiguously "BOM, represented in
790 little-endian format" and cannot be "0xFFFE, represented in big-endian
791 format".
792
793 =item UTF-32, UTF-32BE, UTF32-LE
794
795 The UTF-32 family is pretty much like the UTF-16 family, expect that
796 the units are 32-bit, and therefore the surrogate scheme is not
797 needed.  The BOM signatures will be 0x00 0x00 0xFE 0xFF for BE and
798 0xFF 0xFE 0x00 0x00 for LE.
799
800 =item UCS-2, UCS-4
801
802 Encodings defined by the ISO 10646 standard.  UCS-2 is a 16-bit
803 encoding, UCS-4 is a 32-bit encoding.  Unlike UTF-16, UCS-2
804 is not extensible beyond 0xFFFF, because it does not use surrogates.
805
806 =item UTF-7
807
808 A seven-bit safe (non-eight-bit) encoding, useful if the
809 transport/storage is not eight-bit safe.  Defined by RFC 2152.
810
811 =back
812
813 =head2 Security Implications of Malformed UTF-8
814
815 Unfortunately, the specification of UTF-8 leaves some room for
816 interpretation of how many bytes of encoded output one should generate
817 from one input Unicode character.  Strictly speaking, one is supposed
818 to always generate the shortest possible sequence of UTF-8 bytes,
819 because otherwise there is potential for input buffer overflow at
820 the receiving end of a UTF-8 connection.  Perl always generates the
821 shortest length UTF-8, and with warnings on (C<-w> or C<use
822 warnings;>) Perl will warn about non-shortest length UTF-8 (and other
823 malformations, too, such as the surrogates, which are not real
824 Unicode code points.)
825
826 =head2 Unicode in Perl on EBCDIC
827
828 The way Unicode is handled on EBCDIC platforms is still rather
829 experimental.  On such a platform, references to UTF-8 encoding in this
830 document and elsewhere should be read as meaning UTF-EBCDIC as
831 specified in Unicode Technical Report 16 unless ASCII vs EBCDIC issues
832 are specifically discussed. There is no C<utfebcdic> pragma or
833 ":utfebcdic" layer, rather, "utf8" and ":utf8" are re-used to mean
834 the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic>
835 for more discussion of the issues.
836
837 =head2 Using Unicode in XS
838
839 If you want to handle Perl Unicode in XS extensions, you may find
840 the following C APIs useful:
841
842 =over 4
843
844 =item *
845
846 DO_UTF8(sv) returns true if the UTF8 flag is on and the bytes
847 pragma is not in effect.  SvUTF8(sv) returns true is the UTF8
848 flag is on, the bytes pragma is ignored.  Remember that UTF8
849 flag being on does not mean that there would be any characters
850 of code points greater than 255 or 127 in the scalar, or that
851 there even are any characters in the scalar.  The UTF8 flag
852 means that any characters added to the string will be encoded
853 in UTF8 if the code points of the characters are greater than
854 255.  Not "if greater than 127", since Perl's Unicode model
855 is not to use UTF-8 until it's really necessary.
856
857 =item *
858
859 uvuni_to_utf8(buf, chr) writes a Unicode character code point into a
860 buffer encoding the code point as UTF-8, and returns a pointer
861 pointing after the UTF-8 bytes.
862
863 =item *
864
865 utf8_to_uvuni(buf, lenp) reads UTF-8 encoded bytes from a buffer and
866 returns the Unicode character code point (and optionally the length of
867 the UTF-8 byte sequence).
868
869 =item *
870
871 utf8_length(s, len) returns the length of the UTF-8 encoded buffer in
872 characters.  sv_len_utf8(sv) returns the length of the UTF-8 encoded
873 scalar.
874
875 =item *
876
877 sv_utf8_upgrade(sv) converts the string of the scalar to its UTF-8
878 encoded form.  sv_utf8_downgrade(sv) does the opposite (if possible).
879 sv_utf8_encode(sv) is like sv_utf8_upgrade but the UTF8 flag does not
880 get turned on.  sv_utf8_decode() does the opposite of sv_utf8_encode().
881
882 =item *
883
884 is_utf8_char(buf) returns true if the buffer points to valid UTF-8.
885
886 =item *
887
888 is_utf8_string(buf, len) returns true if the len bytes of the buffer
889 are valid UTF-8.
890
891 =item *
892
893 UTF8SKIP(buf) will return the number of bytes in the UTF-8 encoded
894 character in the buffer.  UNISKIP(chr) will return the number of bytes
895 required to UTF-8-encode the Unicode character code point.
896
897 =item *
898
899 utf8_distance(a, b) will tell the distance in characters between the
900 two pointers pointing to the same UTF-8 encoded buffer.
901
902 =item *
903
904 utf8_hop(s, off) will return a pointer to an UTF-8 encoded buffer that
905 is C<off> (positive or negative) Unicode characters displaced from the
906 UTF-8 buffer C<s>.
907
908 =item *
909
910 pv_uni_display(dsv, spv, len, pvlim, flags) and sv_uni_display(dsv,
911 ssv, pvlim, flags) are useful for debug output of Unicode strings and
912 scalars (only for debug: they display B<all> characters as hexadecimal
913 code points).
914
915 =item *
916
917 ibcmp_utf8(s1, u1, len1, s2, u2, len2) can be used to compare two
918 strings case-insensitively in Unicode.  (For case-sensitive
919 comparisons you can just use memEQ() and memNE() as usual.)
920
921 =back
922
923 For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h>
924 in the Perl source code distribution.
925
926 =head1 SEE ALSO
927
928 L<perluniintro>, L<encoding>, L<Encode>, L<open>, L<utf8>, L<bytes>,
929 L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">
930
931 =cut