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