Integrate mainline. Builds lots of sv.h/embed.h redef warnings
[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 WARNING: While the implementation of Unicode support in Perl is now
10 fairly complete it is still evolving to some extent.
11
12 In particular the way Unicode is handled on EBCDIC platforms is still
13 rather experimental. On such a platform references to UTF-8 encoding
14 in this document and elsewhere should be read as meaning UTF-EBCDIC as
15 specified in Unicode Technical Report 16 unless ASCII vs EBCDIC issues
16 are specifically discussed. There is no C<utfebcdic> pragma or
17 ":utfebcdic" layer, rather "utf8" and ":utf8" are re-used to mean
18 platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic> for
19 more discussion of the issues.
20
21 The following areas are still under development.
22
23 =over 4
24
25 =item Input and Output Disciplines
26
27 A filehandle can be marked as containing perl's internal Unicode
28 encoding (UTF-8 or UTF-EBCDIC) by opening it with the ":utf8" layer.
29 Other encodings can be converted to perl's encoding on input, or from
30 perl's encoding on output by use of the ":encoding()" layer.  There is
31 not yet a clean way to mark the Perl source itself as being in an
32 particular encoding.
33
34 =item Regular Expressions
35
36 The regular expression compiler does now attempt to produce
37 polymorphic opcodes.  That is the pattern should now adapt to the data
38 and automatically switch to the Unicode character scheme when
39 presented with Unicode data, or a traditional byte scheme when
40 presented with byte data.  The implementation is still new and
41 (particularly on EBCDIC platforms) may need further work.
42
43 =item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts
44
45 The C<utf8> pragma implements the tables used for Unicode support.
46 These tables are automatically loaded on demand, so the C<utf8> pragma
47 need not normally be used.
48
49 However, as a compatibility measure, this pragma must be explicitly
50 used to enable recognition of UTF-8 in the Perl scripts themselves on
51 ASCII based machines or recognize UTF-EBCDIC on EBCDIC based machines.
52 B<NOTE: this should be the only place where an explicit C<use utf8> is
53 needed>.
54
55 =back
56
57 =head2 Byte and Character semantics
58
59 Beginning with version 5.6, Perl uses logically wide characters to
60 represent strings internally.  This internal representation of strings
61 uses either the UTF-8 or the UTF-EBCDIC encoding.
62
63 In future, Perl-level operations can be expected to work with
64 characters rather than bytes, in general.
65
66 However, as strictly an interim compatibility measure, Perl aims to
67 provide a safe migration path from byte semantics to character
68 semantics for programs.  For operations where Perl can unambiguously
69 decide that the input data is characters, Perl now switches to
70 character semantics.  For operations where this determination cannot
71 be made without additional information from the user, Perl decides in
72 favor of compatibility, and chooses to use byte semantics.
73
74 This behavior preserves compatibility with earlier versions of Perl,
75 which allowed byte semantics in Perl operations, but only as long as
76 none of the program's inputs are marked as being as source of Unicode
77 character data.  Such data may come from filehandles, from calls to
78 external programs, from information provided by the system (such as %ENV),
79 or from literals and constants in the source text.
80
81 If the C<-C> command line switch is used, (or the
82 ${^WIDE_SYSTEM_CALLS} global flag is set to C<1>), all system calls
83 will use the corresponding wide character APIs.  Note that this is
84 currently only implemented on Windows since other platforms API
85 standard on this area.
86
87 Regardless of the above, the C<bytes> pragma can always be used to
88 force byte semantics in a particular lexical scope.  See L<bytes>.
89
90 The C<utf8> pragma is primarily a compatibility device that enables
91 recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
92 Note that this pragma is only required until a future version of Perl
93 in which character semantics will become the default.  This pragma may
94 then become a no-op.  See L<utf8>.
95
96 Unless mentioned otherwise, Perl operators will use character semantics
97 when they are dealing with Unicode data, and byte semantics otherwise.
98 Thus, character semantics for these operations apply transparently; if
99 the input data came from a Unicode source (for example, by adding a
100 character encoding discipline to the filehandle whence it came, or a
101 literal UTF-8 string constant in the program), character semantics
102 apply; otherwise, byte semantics are in effect.  To force byte semantics
103 on Unicode data, the C<bytes> pragma should be used.
104
105 Notice that if you have a string with byte semantics and you then
106 add character data into it, the bytes will be upgraded I<as if they
107 were ISO 8859-1 (Latin-1)> (or if in EBCDIC, after a translation
108 to ISO 8859-1).
109
110 Under character semantics, many operations that formerly operated on
111 bytes change to operating on characters.  For ASCII data this makes no
112 difference, because UTF-8 stores ASCII in single bytes, but for any
113 character greater than C<chr(127)>, the character B<may> be stored in
114 a sequence of two or more bytes, all of which have the high bit set.
115
116 For C1 controls or Latin 1 characters on an EBCDIC platform the
117 character may be stored in a UTF-EBCDIC multi byte sequence.  But by
118 and large, the user need not worry about this, because Perl hides it
119 from the user.  A character in Perl is logically just a number ranging
120 from 0 to 2**32 or so.  Larger characters encode to longer sequences
121 of bytes internally, but again, this is just an internal detail which
122 is hidden at the Perl level.
123
124 =head2 Effects of character semantics
125
126 Character semantics have the following effects:
127
128 =over 4
129
130 =item *
131
132 Strings and patterns may contain characters that have an ordinal value
133 larger than 255.
134
135 Presuming you use a Unicode editor to edit your program, such
136 characters will typically occur directly within the literal strings as
137 UTF-8 (or UTF-EBCDIC on EBCDIC platforms) characters, but you can also
138 specify a particular character with an extension of the C<\x>
139 notation.  UTF-X characters are specified by putting the hexadecimal
140 code within curlies after the C<\x>.  For instance, a Unicode smiley
141 face is C<\x{263A}>.
142
143 =item *
144
145 Identifiers within the Perl script may contain Unicode alphanumeric
146 characters, including ideographs.  (You are currently on your own when
147 it comes to using the canonical forms of characters--Perl doesn't
148 (yet) attempt to canonicalize variable names for you.)
149
150 =item *
151
152 Regular expressions match characters instead of bytes.  For instance,
153 "." matches a character instead of a byte.  (However, the C<\C> pattern
154 is provided to force a match a single byte ("C<char>" in C, hence C<\C>).)
155
156 =item *
157
158 Character classes in regular expressions match characters instead of
159 bytes, and match against the character properties specified in the
160 Unicode properties database.  So C<\w> can be used to match an
161 ideograph, for instance.
162
163 =item *
164
165 Named Unicode properties and block ranges make be used as character
166 classes via the new C<\p{}> (matches property) and C<\P{}> (doesn't
167 match property) constructs.  For instance, C<\p{Lu}> matches any
168 character with the Unicode uppercase property, while C<\p{M}> matches
169 any mark character.  Single letter properties may omit the brackets,
170 so that can be written C<\pM> also.  Many predefined character classes
171 are available, such as C<\p{IsMirrored}> and C<\p{InTibetan}>.  The
172 recommended names of the C<In> classes are the official Unicode script
173 and block names but with all non-alphanumeric characters removed, for
174 example the block name C<"Latin-1 Supplement"> becomes
175 C<\p{InLatin1Supplement}>.
176
177 Here is the list as of Unicode 3.1.0 (the two-letter classes) and
178 as defined by Perl (the one-letter classes) (in Unicode materials
179 what Perl calls C<L> is often called C<L&>):
180
181    L  Letter
182    Lu Letter, Uppercase
183    Ll Letter, Lowercase
184    Lt Letter, Titlecase
185    Lm Letter, Modifier
186    Lo Letter, Other
187    M  Mark
188    Mn Mark, Non-Spacing
189    Mc Mark, Spacing Combining
190    Me Mark, Enclosing
191    N  Number
192    Nd Number, Decimal Digit
193    Nl Number, Letter
194    No Number, Other
195    P  Punctuation
196    Pc Punctuation, Connector
197    Pd Punctuation, Dash
198    Ps Punctuation, Open
199    Pe Punctuation, Close
200    Pi Punctuation, Initial quote
201        (may behave like Ps or Pe depending on usage)
202    Pf Punctuation, Final quote
203        (may behave like Ps or Pe depending on usage)
204    Po Punctuation, Other
205    S  Symbol
206    Sm Symbol, Math
207    Sc Symbol, Currency
208    Sk Symbol, Modifier
209    So Symbol, Other
210    Z  Separator
211    Zs Separator, Space
212    Zl Separator, Line
213    Zp Separator, Paragraph
214    C  Other
215    Cc Other, Control
216    Cf Other, Format
217    Cs Other, Surrogate
218    Co Other, Private Use
219    Cn Other, Not Assigned (Unicode defines no Cn characters)
220
221 Additionally, because scripts differ in their directionality
222 (for example Hebrew is written right to left), all characters
223 have their directionality defined:
224
225    BidiL   Left-to-Right
226    BidiLRE Left-to-Right Embedding
227    BidiLRO Left-to-Right Override
228    BidiR   Right-to-Left
229    BidiAL  Right-to-Left Arabic
230    BidiRLE Right-to-Left Embedding
231    BidiRLO Right-to-Left Override
232    BidiPDF Pop Directional Format
233    BidiEN  European Number
234    BidiES  European Number Separator
235    BidiET  European Number Terminator
236    BidiAN  Arabic Number
237    BidiCS  Common Number Separator
238    BidiNSM Non-Spacing Mark
239    BidiBN  Boundary Neutral
240    BidiB   Paragraph Separator
241    BidiS   Segment Separator
242    BidiWS  Whitespace
243    BidiON  Other Neutrals
244
245 =head2 Scripts
246
247 The scripts available for C<\p{In...}> and C<\P{In...}>, for example
248 \p{InCyrillic>, are as follows, for example C<\p{InLatin}> or C<\P{InHan}>:
249
250    Latin
251    Greek
252    Cyrillic
253    Armenian
254    Hebrew
255    Arabic
256    Syriac
257    Thaana
258    Devanagari
259    Bengali
260    Gurmukhi
261    Gujarati
262    Oriya
263    Tamil
264    Telugu
265    Kannada
266    Malayalam
267    Sinhala
268    Thai
269    Lao
270    Tibetan
271    Myanmar
272    Georgian
273    Hangul
274    Ethiopic
275    Cherokee
276    CanadianAboriginal
277    Ogham
278    Runic
279    Khmer
280    Mongolian
281    Hiragana
282    Katakana
283    Bopomofo
284    Han
285    Yi
286    OldItalic
287    Gothic
288    Deseret
289    Inherited
290
291 =head2 Blocks
292
293 In addition to B<scripts>, Unicode also defines B<blocks> of
294 characters.  The difference between scripts and blocks is that the
295 former concept is closer to natural languages, while the latter
296 concept is more an artificial grouping based on groups of 256 Unicode
297 characters.  For example, the C<Latin> script contains letters from
298 many blocks, but it does not contain all the characters from those
299 blocks, it does not for example contain digits.
300
301 For more about scripts see the UTR #24:
302 http://www.unicode.org/unicode/reports/tr24/
303 For more about blocks see
304 http://www.unicode.org/Public/UNIDATA/Blocks.txt
305
306 Because there are overlaps in naming (there are, for example, both
307 a script called C<Katakana> and a block called C<Katakana>, the block
308 version has C<Block> appended to its name, C<\p{InKatakanaBlock}>.
309
310 Notice that this definition was introduced in Perl 5.8.0: in Perl
311 5.6.0 only the blocks were used; in Perl 5.8.0 scripts became the
312 preferential character class definition; this meant that the
313 definitions of some character classes changed (the ones in the
314 below list that have the C<Block> appended).
315
316    BasicLatin
317    Latin1Supplement
318    LatinExtendedA
319    LatinExtendedB
320    IPAExtensions
321    SpacingModifierLetters
322    CombiningDiacriticalMarks
323    GreekBlock
324    CyrillicBlock
325    ArmenianBlock
326    HebrewBlock
327    ArabicBlock
328    SyriacBlock
329    ThaanaBlock
330    DevanagariBlock
331    BengaliBlock
332    GurmukhiBlock
333    GujaratiBlock
334    OriyaBlock
335    TamilBlock
336    TeluguBlock
337    KannadaBlock
338    MalayalamBlock
339    SinhalaBlock
340    ThaiBlock
341    LaoBlock
342    TibetanBlock
343    MyanmarBlock
344    GeorgianBlock
345    HangulJamo
346    EthiopicBlock
347    CherokeeBlock
348    UnifiedCanadianAboriginalSyllabics
349    OghamBlock
350    RunicBlock
351    KhmerBlock
352    MongolianBlock
353    LatinExtendedAdditional
354    GreekExtended
355    GeneralPunctuation
356    SuperscriptsandSubscripts
357    CurrencySymbols
358    CombiningMarksforSymbols
359    LetterlikeSymbols
360    NumberForms
361    Arrows
362    MathematicalOperators
363    MiscellaneousTechnical
364    ControlPictures
365    OpticalCharacterRecognition
366    EnclosedAlphanumerics
367    BoxDrawing
368    BlockElements
369    GeometricShapes
370    MiscellaneousSymbols
371    Dingbats
372    BraillePatterns
373    CJKRadicalsSupplement
374    KangxiRadicals
375    IdeographicDescriptionCharacters
376    CJKSymbolsandPunctuation
377    HiraganaBlock
378    KatakanaBlock
379    BopomofoBlock
380    HangulCompatibilityJamo
381    Kanbun
382    BopomofoExtended
383    EnclosedCJKLettersandMonths
384    CJKCompatibility
385    CJKUnifiedIdeographsExtensionA
386    CJKUnifiedIdeographs
387    YiSyllables
388    YiRadicals
389    HangulSyllables
390    HighSurrogates
391    HighPrivateUseSurrogates
392    LowSurrogates
393    PrivateUse
394    CJKCompatibilityIdeographs
395    AlphabeticPresentationForms
396    ArabicPresentationFormsA
397    CombiningHalfMarks
398    CJKCompatibilityForms
399    SmallFormVariants
400    ArabicPresentationFormsB
401    Specials
402    HalfwidthandFullwidthForms
403    OldItalicBlock
404    GothicBlock
405    DeseretBlock
406    ByzantineMusicalSymbols
407    MusicalSymbols
408    MathematicalAlphanumericSymbols
409    CJKUnifiedIdeographsExtensionB
410    CJKCompatibilityIdeographsSupplement
411    Tags
412
413 =item *
414
415 The special pattern C<\X> match matches any extended Unicode sequence
416 (a "combining character sequence" in Standardese), where the first
417 character is a base character and subsequent characters are mark
418 characters that apply to the base character.  It is equivalent to
419 C<(?:\PM\pM*)>.
420
421 =item *
422
423 The C<tr///> operator translates characters instead of bytes.  Note
424 that the C<tr///CU> functionality has been removed, as the interface
425 was a mistake.  For similar functionality see pack('U0', ...) and
426 pack('C0', ...).
427
428 =item *
429
430 Case translation operators use the Unicode case translation tables
431 when provided character input.  Note that C<uc()> translates to
432 uppercase, while C<ucfirst> translates to titlecase (for languages
433 that make the distinction).  Naturally the corresponding backslash
434 sequences have the same semantics.
435
436 =item *
437
438 Most operators that deal with positions or lengths in the string will
439 automatically switch to using character positions, including
440 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
441 C<sprintf()>, C<write()>, and C<length()>.  Operators that
442 specifically don't switch include C<vec()>, C<pack()>, and
443 C<unpack()>.  Operators that really don't care include C<chomp()>, as
444 well as any other operator that treats a string as a bucket of bits,
445 such as C<sort()>, and the operators dealing with filenames.
446
447 =item *
448
449 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
450 since they're often used for byte-oriented formats.  (Again, think
451 "C<char>" in the C language.)  However, there is a new "C<U>" specifier
452 that will convert between UTF-8 characters and integers.  (It works
453 outside of the utf8 pragma too.)
454
455 =item *
456
457 The C<chr()> and C<ord()> functions work on characters.  This is like
458 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
459 C<unpack("C")>.  In fact, the latter are how you now emulate
460 byte-oriented C<chr()> and C<ord()> for Unicode strings.
461 (Note that this reveals the internal UTF-8 encoding of strings and
462 you are not supposed to do that unless you know what you are doing.)
463
464 =item *
465
466 The bit string operators C<& | ^ ~> can operate on character data.
467 However, for backward compatibility reasons (bit string operations
468 when the characters all are less than 256 in ordinal value) one should
469 not mix C<~> (the bit complement) and characters both less than 256 and
470 equal or greater than 256.  Most importantly, the DeMorgan's laws
471 (C<~($x|$y) eq ~$x&~$y>, C<~($x&$y) eq ~$x|~$y>) won't hold.
472 Another way to look at this is that the complement cannot return
473 B<both> the 8-bit (byte) wide bit complement B<and> the full character
474 wide bit complement.
475
476 =item *
477
478 lc(), uc(), lcfirst(), and ucfirst() work only for some of the
479 simplest cases, where the mapping goes from a single Unicode character
480 to another single Unicode character, and where the mapping does not
481 depend on surrounding characters, or on locales.  More complex cases,
482 where for example one character maps into several, are not yet
483 implemented.  See the Unicode Technical Report #21, Case Mappings,
484 for more details.  The Unicode::UCD module (part of Perl since 5.8.0)
485 casespec() and casefold() interfaces supply information about the more
486 complex cases.
487
488 =item *
489
490 And finally, C<scalar reverse()> reverses by character rather than by byte.
491
492 =back
493
494 =head2 Character encodings for input and output
495
496 See L<Encode>.
497
498 =head1 CAVEATS
499
500 As of yet, there is no method for automatically coercing input and
501 output to some encoding other than UTF-8 or UTF-EBCDIC.  This is planned 
502 in the near future, however.
503
504 Whether an arbitrary piece of data will be treated as "characters" or
505 "bytes" by internal operations cannot be divined at the current time.
506
507 Use of locales with utf8 may lead to odd results.  Currently there is
508 some attempt to apply 8-bit locale info to characters in the range
509 0..255, but this is demonstrably incorrect for locales that use
510 characters above that range (when mapped into Unicode).  It will also
511 tend to run slower.  Avoidance of locales is strongly encouraged.
512
513 =head1 UNICODE REGULAR EXPRESSION SUPPORT LEVEL
514
515 The following list of Unicode regular expression support describes
516 feature by feature the Unicode support implemented in Perl as of Perl
517 5.8.0.  The "Level N" and the section numbers refer to the Unicode
518 Technical Report 18, "Unicode Regular Expression Guidelines".
519
520 =over 4
521
522 =item *
523
524 Level 1 - Basic Unicode Support
525
526         2.1 Hex Notation                        - done          [1]
527                 Named Notation                  - done          [2]
528         2.2 Categories                          - done          [3][4]
529         2.3 Subtraction                         - MISSING       [5][6]
530         2.4 Simple Word Boundaries              - done          [7]
531         2.5 Simple Loose Matches                - MISSING       [8]
532         2.6 End of Line                         - MISSING       [9][10]
533
534         [ 1] \x{...}
535         [ 2] \N{...}
536         [ 3] . \p{Is...} \P{Is...}
537         [ 4] now scripts (see UTR#24 Script Names) in  addition to blocks
538         [ 5] have negation
539         [ 6] can use look-ahead to emulate subtracion
540         [ 7] include Letters in word characters
541         [ 8] see UTR#21 Case Mappings
542         [ 9] see UTR#13 Unicode Newline Guidelines
543         [10] should do ^ and $ also on \x{2028} and \x{2029}
544
545 =item *
546
547 Level 2 - Extended Unicode Support
548
549         3.1 Surrogates                          - MISSING
550         3.2 Canonical Equivalents               - MISSING       [11][12]
551         3.3 Locale-Independent Graphemes        - MISSING       [13]
552         3.4 Locale-Independent Words            - MISSING       [14]
553         3.5 Locale-Independent Loose Matches    - MISSING       [15]
554
555         [11] see UTR#15 Unicode Normalization
556         [12] have Unicode::Normalize but not integrated to regexes
557         [13] have \X but at this level . should equal that
558         [14] need three classes, not just \w and \W
559         [15] see UTR#21 Case Mappings
560
561 =item *
562
563 Level 3 - Locale-Sensitive Support
564
565         4.1 Locale-Dependent Categories         - MISSING
566         4.2 Locale-Dependent Graphemes          - MISSING       [16][17]
567         4.3 Locale-Dependent Words              - MISSING
568         4.4 Locale-Dependent Loose Matches      - MISSING
569         4.5 Locale-Dependent Ranges             - MISSING
570
571         [16] see UTR#10 Unicode Collation Algorithms
572         [17] have Unicode::Collate but not integrated to regexes
573
574 =back
575
576 =head1 SEE ALSO
577
578 L<bytes>, L<utf8>, L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">
579
580 =cut