Integrate mainline (Win2k/MinGW all ok except threads/t/end.t)
[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, scripts, and block ranges may be used like
160 character classes via the new C<\p{}> (matches property) and C<\P{}>
161 (doesn't 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 be
165 written C<\pM> also. Many predefined properties are available, such
166 as C<\p{Mirrored}> and C<\p{Tibetan}>.
167
168 The official Unicode script and block names have spaces and dashes as
169 separators, but for convenience you can have dashes, spaces, and underbars
170 at every word division, and you need not care about correct casing. It is
171 recommended, however, that for consistency you use the following naming:
172 the official Unicode script, block, or property name (see below for the
173 additional rules that apply to block names), with whitespace and dashes
174 removed, and the words "uppercase-first-lowercase-rest". That is, "Latin-1
175 Supplement" becomes "Latin1Supplement".
176
177 You can also negate both C<\p{}> and C<\P{}> by introducing a caret
178 (^) between the first curly and the property name: C<\p{^Tamil}> is
179 equal to C<\P{Tamil}>.
180
181 Here are the basic Unicode General Category properties, followed by their
182 long form (you can use either, e.g. C<\p{Lu}> and C<\p{LowercaseLetter}>
183 are identical).
184
185     Short       Long
186
187     L           Letter
188     Lu          UppercaseLetter
189     Ll          LowercaseLetter
190     Lt          TitlecaseLetter
191     Lm          ModifierLetter
192     Lo          OtherLetter
193
194     M           Mark
195     Mn          NonspacingMark
196     Mc          SpacingMark
197     Me          EnclosingMark
198
199     N           Number
200     Nd          DecimalNumber
201     Nl          LetterNumber
202     No          OtherNumber
203
204     P           Punctuation
205     Pc          ConnectorPunctuation
206     Pd          DashPunctuation
207     Ps          OpenPunctuation
208     Pe          ClosePunctuation
209     Pi          InitialPunctuation
210                 (may behave like Ps or Pe depending on usage)
211     Pf          FinalPunctuation
212                 (may behave like Ps or Pe depending on usage)
213     Po          OtherPunctuation
214
215     S           Symbol
216     Sm          MathSymbol
217     Sc          CurrencySymbol
218     Sk          ModifierSymbol
219     So          OtherSymbol
220
221     Z           Separator
222     Zs          SpaceSeparator
223     Zl          LineSeparator
224     Zp          ParagraphSeparator
225
226     C           Other
227     Cc          Control
228     Cf          Format
229     Cs          Surrogate   (not usable)
230     Co          PrivateUse
231     Cn          Unassigned
232
233 The single-letter properties match all characters in any of the
234 two-letter sub-properties starting with the same letter.
235 There's also C<L&> which is an alias for C<Ll>, C<Lu>, and C<Lt>.
236
237 Because Perl hides the need for the user to understand the internal
238 representation of Unicode characters, it has no need to support the
239 somewhat messy concept of surrogates. Therefore, the C<Cs> property is not
240 supported.
241
242 Because scripts differ in their directionality (for example Hebrew is
243 written right to left), Unicode supplies these properties:
244
245     Property    Meaning
246
247     BidiL       Left-to-Right
248     BidiLRE     Left-to-Right Embedding
249     BidiLRO     Left-to-Right Override
250     BidiR       Right-to-Left
251     BidiAL      Right-to-Left Arabic
252     BidiRLE     Right-to-Left Embedding
253     BidiRLO     Right-to-Left Override
254     BidiPDF     Pop Directional Format
255     BidiEN      European Number
256     BidiES      European Number Separator
257     BidiET      European Number Terminator
258     BidiAN      Arabic Number
259     BidiCS      Common Number Separator
260     BidiNSM     Non-Spacing Mark
261     BidiBN      Boundary Neutral
262     BidiB       Paragraph Separator
263     BidiS       Segment Separator
264     BidiWS      Whitespace
265     BidiON      Other Neutrals
266
267 For example, C<\p{BidiR}> matches all characters that are normally
268 written right to left.
269
270 =back
271
272 =head2 Scripts
273
274 The scripts available via C<\p{...}> and C<\P{...}>, for example
275 C<\p{Latin}> or \p{Cyrillic>, are as follows:
276
277     Arabic
278     Armenian
279     Bengali
280     Bopomofo
281     CanadianAboriginal
282     Cherokee
283     Cyrillic
284     Deseret
285     Devanagari
286     Ethiopic
287     Georgian
288     Gothic
289     Greek
290     Gujarati
291     Gurmukhi
292     Han
293     Hangul
294     Hebrew
295     Hiragana
296     Inherited
297     Kannada
298     Katakana
299     Khmer
300     Lao
301     Latin
302     Malayalam
303     Mongolian
304     Myanmar
305     Ogham
306     OldItalic
307     Oriya
308     Runic
309     Sinhala
310     Syriac
311     Tamil
312     Telugu
313     Thaana
314     Thai
315     Tibetan
316     Yi
317
318 There are also extended property classes that supplement the basic
319 properties, defined by the F<PropList> Unicode database:
320
321     ASCII_Hex_Digit
322     BidiControl
323     Dash
324     Diacritic
325     Extender
326     HexDigit
327     Hyphen
328     Ideographic
329     JoinControl
330     NoncharacterCodePoint
331     OtherAlphabetic
332     OtherLowercase
333     OtherMath
334     OtherUppercase
335     QuotationMark
336     WhiteSpace
337
338 and further derived properties:
339
340     Alphabetic      Lu + Ll + Lt + Lm + Lo + OtherAlphabetic
341     Lowercase       Ll + OtherLowercase
342     Uppercase       Lu + OtherUppercase
343     Math            Sm + OtherMath
344
345     ID_Start        Lu + Ll + Lt + Lm + Lo + Nl
346     ID_Continue     ID_Start + Mn + Mc + Nd + Pc
347
348     Any             Any character
349     Assigned        Any non-Cn character (i.e. synonym for C<\P{Cn}>)
350     Unassigned      Synonym for C<\p{Cn}>
351     Common          Any character (or unassigned code point)
352                     not explicitly assigned to a script
353
354 For backward compatability, all properties mentioned so far may have C<Is>
355 prepended to their name (e.g. C<\P{IsLu}> is equal to C<\P{Lu}>).
356
357 =head2 Blocks
358
359 In addition to B<scripts>, Unicode also defines B<blocks> of characters.
360 The difference between scripts and blocks is that the scripts concept is
361 closer to natural languages, while the blocks concept is more an artificial
362 grouping based on groups of mostly 256 Unicode characters. For example, the
363 C<Latin> script contains letters from many blocks. On the other hand, the
364 C<Latin> script does not contain all the characters from those blocks. It
365 does not, for example, contain digits because digits are shared across many
366 scripts. Digits and other similar groups, like punctuation, are in a
367 category called C<Common>.
368
369 For more about scripts, see the UTR #24:
370
371    http://www.unicode.org/unicode/reports/tr24/
372
373 For more about blocks, see:
374
375    http://www.unicode.org/Public/UNIDATA/Blocks.txt
376
377 Blocks names are given with the C<In> prefix. For example, the
378 Katakana block is referenced via C<\p{InKatakana}>. The C<In>
379 prefix may be omitted if there is no nameing conflict with a script
380 or any other property, but it is recommended that C<In> always be used
381 to avoid confusion.
382
383 These block names are supported:
384
385    InAlphabeticPresentationForms
386    InArabicBlock
387    InArabicPresentationFormsA
388    InArabicPresentationFormsB
389    InArmenianBlock
390    InArrows
391    InBasicLatin
392    InBengaliBlock
393    InBlockElements
394    InBopomofoBlock
395    InBopomofoExtended
396    InBoxDrawing
397    InBraillePatterns
398    InByzantineMusicalSymbols
399    InCJKCompatibility
400    InCJKCompatibilityForms
401    InCJKCompatibilityIdeographs
402    InCJKCompatibilityIdeographsSupplement
403    InCJKRadicalsSupplement
404    InCJKSymbolsAndPunctuation
405    InCJKUnifiedIdeographs
406    InCJKUnifiedIdeographsExtensionA
407    InCJKUnifiedIdeographsExtensionB
408    InCherokeeBlock
409    InCombiningDiacriticalMarks
410    InCombiningHalfMarks
411    InCombiningMarksForSymbols
412    InControlPictures
413    InCurrencySymbols
414    InCyrillicBlock
415    InDeseretBlock
416    InDevanagariBlock
417    InDingbats
418    InEnclosedAlphanumerics
419    InEnclosedCJKLettersAndMonths
420    InEthiopicBlock
421    InGeneralPunctuation
422    InGeometricShapes
423    InGeorgianBlock
424    InGothicBlock
425    InGreekBlock
426    InGreekExtended
427    InGujaratiBlock
428    InGurmukhiBlock
429    InHalfwidthAndFullwidthForms
430    InHangulCompatibilityJamo
431    InHangulJamo
432    InHangulSyllables
433    InHebrewBlock
434    InHighPrivateUseSurrogates
435    InHighSurrogates
436    InHiraganaBlock
437    InIPAExtensions
438    InIdeographicDescriptionCharacters
439    InKanbun
440    InKangxiRadicals
441    InKannadaBlock
442    InKatakanaBlock
443    InKhmerBlock
444    InLaoBlock
445    InLatin1Supplement
446    InLatinExtendedAdditional
447    InLatinExtended-A
448    InLatinExtended-B
449    InLetterlikeSymbols
450    InLowSurrogates
451    InMalayalamBlock
452    InMathematicalAlphanumericSymbols
453    InMathematicalOperators
454    InMiscellaneousSymbols
455    InMiscellaneousTechnical
456    InMongolianBlock
457    InMusicalSymbols
458    InMyanmarBlock
459    InNumberForms
460    InOghamBlock
461    InOldItalicBlock
462    InOpticalCharacterRecognition
463    InOriyaBlock
464    InPrivateUse
465    InRunicBlock
466    InSinhalaBlock
467    InSmallFormVariants
468    InSpacingModifierLetters
469    InSpecials
470    InSuperscriptsAndSubscripts
471    InSyriacBlock
472    InTags
473    InTamilBlock
474    InTeluguBlock
475    InThaanaBlock
476    InThaiBlock
477    InTibetanBlock
478    InUnifiedCanadianAboriginalSyllabics
479    InYiRadicals
480    InYiSyllables
481
482 =over 4
483
484 =item *
485
486 The special pattern C<\X> matches any extended Unicode sequence
487 (a "combining character sequence" in Standardese), where the first
488 character is a base character and subsequent characters are mark
489 characters that apply to the base character.  It is equivalent to
490 C<(?:\PM\pM*)>.
491
492 =item *
493
494 The C<tr///> operator translates characters instead of bytes.  Note
495 that the C<tr///CU> functionality has been removed, as the interface
496 was a mistake.  For similar functionality see pack('U0', ...) and
497 pack('C0', ...).
498
499 =item *
500
501 Case translation operators use the Unicode case translation tables
502 when provided character input.  Note that C<uc()> (also known as C<\U>
503 in doublequoted strings) translates to uppercase, while C<ucfirst>
504 (also known as C<\u> in doublequoted strings) translates to titlecase
505 (for languages that make the distinction).  Naturally the
506 corresponding backslash sequences have the same semantics.
507
508 =item *
509
510 Most operators that deal with positions or lengths in the string will
511 automatically switch to using character positions, including
512 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
513 C<sprintf()>, C<write()>, and C<length()>.  Operators that
514 specifically don't switch include C<vec()>, C<pack()>, and
515 C<unpack()>.  Operators that really don't care include C<chomp()>, as
516 well as any other operator that treats a string as a bucket of bits,
517 such as C<sort()>, and the operators dealing with filenames.
518
519 =item *
520
521 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
522 since they're often used for byte-oriented formats.  (Again, think
523 "C<char>" in the C language.)  However, there is a new "C<U>" specifier
524 that will convert between Unicode characters and integers.
525
526 =item *
527
528 The C<chr()> and C<ord()> functions work on characters.  This is like
529 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
530 C<unpack("C")>.  In fact, the latter are how you now emulate
531 byte-oriented C<chr()> and C<ord()> for Unicode strings.
532 (Note that this reveals the internal encoding of Unicode strings,
533 which is not something one normally needs to care about at all.)
534
535 =item *
536
537 The bit string operators C<& | ^ ~> can operate on character data.
538 However, for backward compatibility reasons (bit string operations
539 when the characters all are less than 256 in ordinal value) one should
540 not mix C<~> (the bit complement) and characters both less than 256 and
541 equal or greater than 256.  Most importantly, the DeMorgan's laws
542 (C<~($x|$y) eq ~$x&~$y>, C<~($x&$y) eq ~$x|~$y>) won't hold.
543 Another way to look at this is that the complement cannot return
544 B<both> the 8-bit (byte) wide bit complement B<and> the full character
545 wide bit complement.
546
547 =item *
548
549 lc(), uc(), lcfirst(), and ucfirst() work for the following cases:
550
551 =over 8
552
553 =item *
554
555 the case mapping is from a single Unicode character to another
556 single Unicode character
557
558 =item *
559
560 the case mapping is from a single Unicode character to more
561 than one Unicode character
562
563 =back
564
565 What doesn't yet work are the following cases:
566
567 =over 8
568
569 =item *
570
571 the "final sigma" (Greek)
572
573 =item *
574
575 anything to with locales (Lithuanian, Turkish, Azeri)
576
577 =back
578
579 See the Unicode Technical Report #21, Case Mappings, for more details.
580
581 =item *
582
583 And finally, C<scalar reverse()> reverses by character rather than by byte.
584
585 =back
586
587 =head2 Character encodings for input and output
588
589 See L<Encode>.
590
591 =head2 Unicode Regular Expression Support Level
592
593 The following list of Unicode regular expression support describes
594 feature by feature the Unicode support implemented in Perl as of Perl
595 5.8.0.  The "Level N" and the section numbers refer to the Unicode
596 Technical Report 18, "Unicode Regular Expression Guidelines".
597
598 =over 4
599
600 =item *
601
602 Level 1 - Basic Unicode Support
603
604         2.1 Hex Notation                        - done          [1]
605             Named Notation                      - done          [2]
606         2.2 Categories                          - done          [3][4]
607         2.3 Subtraction                         - MISSING       [5][6]
608         2.4 Simple Word Boundaries              - done          [7]
609         2.5 Simple Loose Matches                - done          [8]
610         2.6 End of Line                         - MISSING       [9][10]
611
612         [ 1] \x{...}
613         [ 2] \N{...}
614         [ 3] . \p{...} \P{...}
615         [ 4] now scripts (see UTR#24 Script Names) in addition to blocks
616         [ 5] have negation
617         [ 6] can use look-ahead to emulate subtraction (*)
618         [ 7] include Letters in word characters
619         [ 8] note that perl does Full casefolding in matching, not Simple:
620              for example U+1F88 is equivalent with U+1F000 U+03B9,
621              not with 1F80.  This difference matters for certain Greek
622              capital letters with certain modifiers: the Full casefolding
623              decomposes the letter, while the Simple casefolding would map
624              it to a single character.
625         [ 9] see UTR#13 Unicode Newline Guidelines
626         [10] should do ^ and $ also on \x{85}, \x{2028} and \x{2029})
627              (should also affect <>, $., and script line numbers)
628              (the \x{85}, \x{2028} and \x{2029} do match \s)
629
630 (*) You can mimic class subtraction using lookahead.
631 For example, what TR18 might write as
632
633     [{Greek}-[{UNASSIGNED}]]
634
635 in Perl can be written as:
636
637     (?!\p{Unassigned})\p{InGreek}
638     (?=\p{Assigned})\p{InGreek}
639
640 But in this particular example, you probably really want
641
642     \p{Greek}
643
644 which will match assigned characters known to be part of the Greek script.
645
646 =item *
647
648 Level 2 - Extended Unicode Support
649
650         3.1 Surrogates                          - MISSING
651         3.2 Canonical Equivalents               - MISSING       [11][12]
652         3.3 Locale-Independent Graphemes        - MISSING       [13]
653         3.4 Locale-Independent Words            - MISSING       [14]
654         3.5 Locale-Independent Loose Matches    - MISSING       [15]
655
656         [11] see UTR#15 Unicode Normalization
657         [12] have Unicode::Normalize but not integrated to regexes
658         [13] have \X but at this level . should equal that
659         [14] need three classes, not just \w and \W
660         [15] see UTR#21 Case Mappings
661
662 =item *
663
664 Level 3 - Locale-Sensitive Support
665
666         4.1 Locale-Dependent Categories         - MISSING
667         4.2 Locale-Dependent Graphemes          - MISSING       [16][17]
668         4.3 Locale-Dependent Words              - MISSING
669         4.4 Locale-Dependent Loose Matches      - MISSING
670         4.5 Locale-Dependent Ranges             - MISSING
671
672         [16] see UTR#10 Unicode Collation Algorithms
673         [17] have Unicode::Collate but not integrated to regexes
674
675 =back
676
677 =head2 Unicode Encodings
678
679 Unicode characters are assigned to I<code points> which are abstract
680 numbers.  To use these numbers various encodings are needed.
681
682 =over 4
683
684 =item *
685
686 UTF-8
687
688 UTF-8 is a variable-length (1 to 6 bytes, current character allocations
689 require 4 bytes), byteorder independent encoding. For ASCII, UTF-8 is
690 transparent (and we really do mean 7-bit ASCII, not another 8-bit encoding).
691
692 The following table is from Unicode 3.2.
693
694  Code Points            1st Byte  2nd Byte  3rd Byte  4th Byte
695
696    U+0000..U+007F       00..7F
697    U+0080..U+07FF       C2..DF    80..BF
698    U+0800..U+0FFF       E0        A0..BF    80..BF  
699    U+1000..U+CFFF       E1..EC    80..BF    80..BF  
700    U+D000..U+D7FF       ED        80..9F    80..BF  
701    U+D800..U+DFFF       ******* ill-formed *******
702    U+E000..U+FFFF       EE..EF    80..BF    80..BF  
703   U+10000..U+3FFFF      F0        90..BF    80..BF    80..BF
704   U+40000..U+FFFFF      F1..F3    80..BF    80..BF    80..BF
705  U+100000..U+10FFFF     F4        80..8F    80..BF    80..BF
706
707 Note the A0..BF in U+0800..U+0FFF, the 80..9F in U+D000...U+D7FF,
708 the 90..BF in U+10000..U+3FFFF, and the 80...8F in U+100000..U+10FFFF.
709 Or, another way to look at it, as bits:
710
711  Code Points                    1st Byte   2nd Byte  3rd Byte  4th Byte
712
713                     0aaaaaaa     0aaaaaaa
714             00000bbbbbaaaaaa     110bbbbb  10aaaaaa
715             ccccbbbbbbaaaaaa     1110cccc  10bbbbbb  10aaaaaa
716   00000dddccccccbbbbbbaaaaaa     11110ddd  10cccccc  10bbbbbb  10aaaaaa
717
718 As you can see, the continuation bytes all begin with C<10>, and the
719 leading bits of the start byte tell how many bytes the are in the
720 encoded character.
721
722 =item *
723
724 UTF-EBCDIC
725
726 Like UTF-8, but EBCDIC-safe, as UTF-8 is ASCII-safe.
727
728 =item *
729
730 UTF-16, UTF-16BE, UTF16-LE, Surrogates, and BOMs (Byte Order Marks)
731
732 (The followings items are mostly for reference, Perl doesn't
733 use them internally.)
734
735 UTF-16 is a 2 or 4 byte encoding.  The Unicode code points
736 0x0000..0xFFFF are stored in two 16-bit units, and the code points
737 0x010000..0x10FFFF in two 16-bit units.  The latter case is
738 using I<surrogates>, the first 16-bit unit being the I<high
739 surrogate>, and the second being the I<low surrogate>.
740
741 Surrogates are code points set aside to encode the 0x01000..0x10FFFF
742 range of Unicode code points in pairs of 16-bit units.  The I<high
743 surrogates> are the range 0xD800..0xDBFF, and the I<low surrogates>
744 are the range 0xDC00..0xDFFFF.  The surrogate encoding is
745
746         $hi = ($uni - 0x10000) / 0x400 + 0xD800;
747         $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
748
749 and the decoding is
750
751         $uni = 0x10000 + ($hi - 0xD8000) * 0x400 + ($lo - 0xDC00);
752
753 If you try to generate surrogates (for example by using chr()), you
754 will get a warning if warnings are turned on (C<-w> or C<use
755 warnings;>) because those code points are not valid for a Unicode
756 character.
757
758 Because of the 16-bitness, UTF-16 is byteorder dependent.  UTF-16
759 itself can be used for in-memory computations, but if storage or
760 transfer is required, either UTF-16BE (Big Endian) or UTF-16LE
761 (Little Endian) must be chosen.
762
763 This introduces another problem: what if you just know that your data
764 is UTF-16, but you don't know which endianness?  Byte Order Marks
765 (BOMs) are a solution to this.  A special character has been reserved
766 in Unicode to function as a byte order marker: the character with the
767 code point 0xFEFF is the BOM.
768
769 The trick is that if you read a BOM, you will know the byte order,
770 since if it was written on a big endian platform, you will read the
771 bytes 0xFE 0xFF, but if it was written on a little endian platform,
772 you will read the bytes 0xFF 0xFE.  (And if the originating platform
773 was writing in UTF-8, you will read the bytes 0xEF 0xBB 0xBF.)
774
775 The way this trick works is that the character with the code point
776 0xFFFE is guaranteed not to be a valid Unicode character, so the
777 sequence of bytes 0xFF 0xFE is unambiguously "BOM, represented in
778 little-endian format" and cannot be "0xFFFE, represented in big-endian
779 format".
780
781 =item *
782
783 UTF-32, UTF-32BE, UTF32-LE
784
785 The UTF-32 family is pretty much like the UTF-16 family, expect that
786 the units are 32-bit, and therefore the surrogate scheme is not
787 needed.  The BOM signatures will be 0x00 0x00 0xFE 0xFF for BE and
788 0xFF 0xFE 0x00 0x00 for LE.
789
790 =item *
791
792 UCS-2, UCS-4
793
794 Encodings defined by the ISO 10646 standard.  UCS-2 is a 16-bit
795 encoding, UCS-4 is a 32-bit encoding.  Unlike UTF-16, UCS-2
796 is not extensible beyond 0xFFFF, because it does not use surrogates.
797
798 =item *
799
800 UTF-7
801
802 A seven-bit safe (non-eight-bit) encoding, useful if the
803 transport/storage is not eight-bit safe.  Defined by RFC 2152.
804
805 =back
806
807 =head2 Security Implications of Malformed UTF-8
808
809 Unfortunately, the specification of UTF-8 leaves some room for
810 interpretation of how many bytes of encoded output one should generate
811 from one input Unicode character.  Strictly speaking, one is supposed
812 to always generate the shortest possible sequence of UTF-8 bytes,
813 because otherwise there is potential for input buffer overflow at
814 the receiving end of a UTF-8 connection.  Perl always generates the
815 shortest length UTF-8, and with warnings on (C<-w> or C<use
816 warnings;>) Perl will warn about non-shortest length UTF-8 (and other
817 malformations, too, such as the surrogates, which are not real
818 Unicode 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 Locales
832
833 Usually locale settings and Unicode do not affect each other, but
834 there are a couple of exceptions:
835
836 =over 4
837
838 =item *
839
840 If your locale environment variables (LANGUAGE, LC_ALL, LC_CTYPE, LANG)
841 contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
842 the default encoding of your STDIN, STDOUT, and STDERR, and of
843 B<any subsequent file open>, is UTF-8.
844
845 =item *
846
847 Perl tries really hard to work both with Unicode and the old byte
848 oriented world: most often this is nice, but sometimes this causes
849 problems.  See L</BUGS> for example how sometimes using locales
850 with Unicode can help with these problems.
851
852 =back
853
854 =head2 Using Unicode in XS
855
856 If you want to handle Perl Unicode in XS extensions, you may find
857 the following C APIs useful (see perlapi for details):
858
859 =over 4
860
861 =item *
862
863 DO_UTF8(sv) returns true if the UTF8 flag is on and the bytes pragma
864 is not in effect.  SvUTF8(sv) returns true is the UTF8 flag is on, the
865 bytes pragma is ignored.  The UTF8 flag being on does B<not> mean that
866 there are any characters of code points greater than 255 (or 127) in
867 the scalar, or that there even are any characters in the scalar.
868 What the UTF8 flag means is that the sequence of octets in the
869 representation of the scalar is the sequence of UTF-8 encoded
870 code points of the characters of a string.  The UTF8 flag being
871 off means that each octet in this representation encodes a single
872 character with codepoint 0..255 within the string.  Perl's Unicode
873 model is not to use UTF-8 until it's really necessary.
874
875 =item *
876
877 uvuni_to_utf8(buf, chr) writes a Unicode character code point into a
878 buffer encoding the code point as UTF-8, and returns a pointer
879 pointing after the UTF-8 bytes.
880
881 =item *
882
883 utf8_to_uvuni(buf, lenp) reads UTF-8 encoded bytes from a buffer and
884 returns the Unicode character code point (and optionally the length of
885 the UTF-8 byte sequence).
886
887 =item *
888
889 utf8_length(start, end) returns the length of the UTF-8 encoded buffer
890 in characters.  sv_len_utf8(sv) returns the length of the UTF-8 encoded
891 scalar.
892
893 =item *
894
895 sv_utf8_upgrade(sv) converts the string of the scalar to its UTF-8
896 encoded form.  sv_utf8_downgrade(sv) does the opposite (if possible).
897 sv_utf8_encode(sv) is like sv_utf8_upgrade but the UTF8 flag does not
898 get turned on.  sv_utf8_decode() does the opposite of sv_utf8_encode().
899 Note that none of these are to be used as general purpose encoding/decoding
900 interfaces: use Encode for that.  sv_utf8_upgrade() is affected by the
901 encoding pragma, but sv_utf8_downgrade() is not (since the encoding
902 pragma is designed to be a one-way street).
903
904 =item *
905
906 is_utf8_char(s) returns true if the pointer points to a valid UTF-8
907 character.
908
909 =item *
910
911 is_utf8_string(buf, len) returns true if the len bytes of the buffer
912 are valid UTF-8.
913
914 =item *
915
916 UTF8SKIP(buf) will return the number of bytes in the UTF-8 encoded
917 character in the buffer.  UNISKIP(chr) will return the number of bytes
918 required to UTF-8-encode the Unicode character code point.  UTF8SKIP()
919 is useful for example for iterating over the characters of a UTF-8
920 encoded buffer; UNISKIP() is useful for example in computing
921 the size required for a UTF-8 encoded buffer.
922
923 =item *
924
925 utf8_distance(a, b) will tell the distance in characters between the
926 two pointers pointing to the same UTF-8 encoded buffer.
927
928 =item *
929
930 utf8_hop(s, off) will return a pointer to an UTF-8 encoded buffer that
931 is C<off> (positive or negative) Unicode characters displaced from the
932 UTF-8 buffer C<s>.  Be careful not to overstep the buffer: utf8_hop()
933 will merrily run off the end or the beginning if told to do so.
934
935 =item *
936
937 pv_uni_display(dsv, spv, len, pvlim, flags) and sv_uni_display(dsv,
938 ssv, pvlim, flags) are useful for debug output of Unicode strings and
939 scalars.  By default they are useful only for debug: they display
940 B<all> characters as hexadecimal code points, but with the flags
941 UNI_DISPLAY_ISPRINT and UNI_DISPLAY_BACKSLASH you can make the output
942 more readable.
943
944 =item *
945
946 ibcmp_utf8(s1, pe1, u1, l1, u1, s2, pe2, l2, u2) can be used to
947 compare two strings case-insensitively in Unicode.
948 (For case-sensitive comparisons you can just use memEQ() and memNE()
949 as usual.)
950
951 =back
952
953 For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h>
954 in the Perl source code distribution.
955
956 =head1 BUGS
957
958 Use of locales with Unicode data may lead to odd results.  Currently
959 there is some attempt to apply 8-bit locale info to characters in the
960 range 0..255, but this is demonstrably incorrect for locales that use
961 characters above that range when mapped into Unicode.  It will also
962 tend to run slower.  Avoidance of locales is strongly encouraged,
963 with one known expection, see the next paragraph.
964
965 If the keys of a hash are "mixed", that is, some keys are Unicode,
966 while some keys are "byte", the keys may behave differently in regular
967 expressions since the definition of character classes like C</\w/>
968 is different for byte strings and character strings.  This problem can
969 sometimes be helped by using an appropriate locale (see L<perllocale>).
970 Another way is to force all the strings to be character encoded by
971 using utf8::upgrade() (see L<utf8>).
972
973 Some functions are slower when working on UTF-8 encoded strings than
974 on byte encoded strings. All functions that need to hop over
975 characters such as length(), substr() or index() can work B<much>
976 faster when the underlying data are byte-encoded. Witness the
977 following benchmark:
978
979   % perl -e '
980   use Benchmark;
981   use strict;
982   our $l = 10000;
983   our $u = our $b = "x" x $l;
984   substr($u,0,1) = "\x{100}";
985   timethese(-2,{
986   LENGTH_B => q{ length($b) },
987   LENGTH_U => q{ length($u) },
988   SUBSTR_B => q{ substr($b, $l/4, $l/2) },
989   SUBSTR_U => q{ substr($u, $l/4, $l/2) },
990   });
991   '
992   Benchmark: running LENGTH_B, LENGTH_U, SUBSTR_B, SUBSTR_U for at least 2 CPU seconds...
993     LENGTH_B:  2 wallclock secs ( 2.36 usr +  0.00 sys =  2.36 CPU) @ 5649983.05/s (n=13333960)
994     LENGTH_U:  2 wallclock secs ( 2.11 usr +  0.00 sys =  2.11 CPU) @ 12155.45/s (n=25648)
995     SUBSTR_B:  3 wallclock secs ( 2.16 usr +  0.00 sys =  2.16 CPU) @ 374480.09/s (n=808877)
996     SUBSTR_U:  2 wallclock secs ( 2.11 usr +  0.00 sys =  2.11 CPU) @ 6791.00/s (n=14329)
997
998 The numbers show an incredible slowness on long UTF-8 strings and you
999 should carefully avoid to use these functions within tight loops. For
1000 example if you want to iterate over characters, it is infinitely
1001 better to split into an array than to use substr, as the following
1002 benchmark shows:
1003
1004   % perl -e '
1005   use Benchmark;
1006   use strict;
1007   our $l = 10000;
1008   our $u = our $b = "x" x $l;
1009   substr($u,0,1) = "\x{100}";
1010   timethese(-5,{
1011   SPLIT_B => q{ for my $c (split //, $b){}  },
1012   SPLIT_U => q{ for my $c (split //, $u){}  },
1013   SUBSTR_B => q{ for my $i (0..length($b)-1){my $c = substr($b,$i,1);} },
1014   SUBSTR_U => q{ for my $i (0..length($u)-1){my $c = substr($u,$i,1);} },
1015   });
1016   '
1017   Benchmark: running SPLIT_B, SPLIT_U, SUBSTR_B, SUBSTR_U for at least 5 CPU seconds...
1018      SPLIT_B:  6 wallclock secs ( 5.29 usr +  0.00 sys =  5.29 CPU) @ 56.14/s (n=297)
1019      SPLIT_U:  5 wallclock secs ( 5.17 usr +  0.01 sys =  5.18 CPU) @ 55.21/s (n=286)
1020     SUBSTR_B:  5 wallclock secs ( 5.34 usr +  0.00 sys =  5.34 CPU) @ 123.22/s (n=658)
1021     SUBSTR_U:  7 wallclock secs ( 6.20 usr +  0.00 sys =  6.20 CPU) @  0.81/s (n=5)
1022
1023 You see, the algorithm based on substr() was faster with byte encoded
1024 data but it is pathologically slow with UTF-8 data.
1025
1026 =head1 SEE ALSO
1027
1028 L<perluniintro>, L<encoding>, L<Encode>, L<open>, L<utf8>, L<bytes>,
1029 L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">
1030
1031 =cut