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