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