PERL_MM_USE_DEFAULT
[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}>.
172
173 The C<\p{Is...}> test for "general properties" such as "letter",
174 "digit", while the C<\p{In...}> test for Unicode scripts and blocks.
175
176 The official Unicode script and block names have spaces and
177 dashes and separators, but for convenience you can have
178 dashes, spaces, and underbars at every word division, and
179 you need not care about correct casing.  It is recommended,
180 however, that for consistency you use the following naming:
181 the official Unicode script or block name (see below for
182 the additional rules that apply to block names), with the whitespace
183 and dashes removed, and the words "uppercase-first-lowercase-otherwise".
184 That is, "Latin-1 Supplement" becomes "Latin1Supplement".
185
186 You can also negate both C<\p{}> and C<\P{}> by introducing a caret
187 (^) between the first curly and the property name: C<\p{^InTamil}> is
188 equal to C<\P{InTamil}>.
189
190 The C<In> and C<Is> can be left out: C<\p{Greek}> is equal to
191 C<\p{InGreek}>, C<\P{Pd}> is equal to C<\P{Pd}>.
192
193     Short       Long
194
195     L           Letter
196     Lu          Uppercase Letter
197     Ll          Lowercase Letter
198     Lt          Titlecase Letter
199     Lm          Modifier Letter
200     Lo          Other Letter
201
202     M           Mark
203     Mn          Non-Spacing Mark
204     Mc          Spacing Combining Mark
205     Me          Enclosing Mark
206
207     N           Number
208     Nd          Decimal Digit Number
209     Nl          Letter Number
210     No          Other Number
211
212     P           Punctuation
213     Pc          Connector Punctuation
214     Pd          Dash Punctuation
215     Ps          Open Punctuation
216     Pe          Close Punctuation
217     Pi          Initial Punctuation
218                 (may behave like Ps or Pe depending on usage)
219     Pf          Final Punctuation
220                 (may behave like Ps or Pe depending on usage)
221     Po          Other Punctuation
222
223     S           Symbol
224     Sm          Math Symbol
225     Sc          Currency Symbol
226     Sk          Modifier Symbol
227     So          Other Symbol
228
229     Z           Separator
230     Zs          Space Separator
231     Zl          Line Separator
232     Zp          Paragraph Separator
233
234     C           Other
235     Cc          (Other) Control
236     Cf          (Other) Format
237     Cs          (Other) Surrogate
238     Co          (Other) Private Use
239     Cn          (Other) Not Assigned
240
241 There's also C<L&> which is an alias for C<Ll>, C<Lu>, and C<Lt>.
242
243 The following reserved ranges have C<In> tests:
244
245     CJK Ideograph Extension A
246     CJK Ideograph
247     Hangul Syllable
248     Non Private Use High Surrogate
249     Private Use High Surrogate
250     Low Surrogate
251     Private Surrogate
252     CJK Ideograph Extension B
253     Plane 15 Private Use
254     Plane 16 Private Use
255
256 For example C<"\x{AC00}" =~ \p{HangulSyllable}> will test true.
257 (Handling of surrogates is not implemented yet.)
258
259 Additionally, because scripts differ in their directionality
260 (for example Hebrew is written right to left), all characters
261 have their directionality defined:
262
263     BidiL       Left-to-Right
264     BidiLRE     Left-to-Right Embedding
265     BidiLRO     Left-to-Right Override
266     BidiR       Right-to-Left
267     BidiAL      Right-to-Left Arabic
268     BidiRLE     Right-to-Left Embedding
269     BidiRLO     Right-to-Left Override
270     BidiPDF     Pop Directional Format
271     BidiEN      European Number
272     BidiES      European Number Separator
273     BidiET      European Number Terminator
274     BidiAN      Arabic Number
275     BidiCS      Common Number Separator
276     BidiNSM     Non-Spacing Mark
277     BidiBN      Boundary Neutral
278     BidiB       Paragraph Separator
279     BidiS       Segment Separator
280     BidiWS      Whitespace
281     BidiON      Other Neutrals
282
283 =head2 Scripts
284
285 The scripts available for C<\p{In...}> and C<\P{In...}>, for example
286 \p{InCyrillic>, are as follows, for example C<\p{InLatin}> or C<\P{InHan}>:
287
288     Latin
289     Greek
290     Cyrillic
291     Armenian
292     Hebrew
293     Arabic
294     Syriac
295     Thaana
296     Devanagari
297     Bengali
298     Gurmukhi
299     Gujarati
300     Oriya
301     Tamil
302     Telugu
303     Kannada
304     Malayalam
305     Sinhala
306     Thai
307     Lao
308     Tibetan
309     Myanmar
310     Georgian
311     Hangul
312     Ethiopic
313     Cherokee
314     Canadian Aboriginal
315     Ogham
316     Runic
317     Khmer
318     Mongolian
319     Hiragana
320     Katakana
321     Bopomofo
322     Han
323     Yi
324     Old Italic
325     Gothic
326     Deseret
327     Inherited
328
329 There are also extended property classes that supplement the basic
330 properties, defined by the F<PropList> Unicode database:
331
332     White_space
333     Bidi_Control
334     Join_Control
335     Dash
336     Hyphen
337     Quotation_Mark
338     Other_Math
339     Hex_Digit
340     ASCII_Hex_Digit
341     Other_Alphabetic
342     Ideographic
343     Diacritic
344     Extender
345     Other_Lowercase
346     Other_Uppercase
347     Noncharacter_Code_Point
348
349 and further derived properties:
350
351     Alphabetic      Lu + Ll + Lt + Lm + Lo + Other_Alphabetic
352     Lowercase       Ll + Other_Lowercase
353     Uppercase       Lu + Other_Uppercase
354     Math            Sm + Other_Math
355
356     ID_Start        Lu + Ll + Lt + Lm + Lo + Nl
357     ID_Continue     ID_Start + Mn + Mc + Nd + Pc
358
359     Any             Any character
360     Assigned        Any non-Cn character
361     Common          Any character (or unassigned code point)
362                     not explicitly assigned to a script.
363
364 =head2 Blocks
365
366 In addition to B<scripts>, Unicode also defines B<blocks> of
367 characters.  The difference between scripts and blocks is that the
368 former concept is closer to natural languages, while the latter
369 concept is more an artificial grouping based on groups of 256 Unicode
370 characters.  For example, the C<Latin> script contains letters from
371 many blocks, but it does not contain all the characters from those
372 blocks, it does not for example contain digits.
373
374 For more about scripts see the UTR #24:
375 http://www.unicode.org/unicode/reports/tr24/
376 For more about blocks see
377 http://www.unicode.org/Public/UNIDATA/Blocks.txt
378
379 Because there are overlaps in naming (there are, for example, both
380 a script called C<Katakana> and a block called C<Katakana>, the block
381 version has C<Block> appended to its name, C<\p{InKatakanaBlock}>.
382
383 Notice that this definition was introduced in Perl 5.8.0: in Perl
384 5.6.0 only the blocks were used; in Perl 5.8.0 scripts became the
385 preferential Unicode character class definition; this meant that
386 the definitions of some character classes changed (the ones in the
387 below list that have the C<Block> appended).
388
389    Basic Latin
390    Latin 1 Supplement
391    Latin Extended-A
392    Latin Extended-B
393    IPA Extensions
394    Spacing Modifier Letters
395    Combining Diacritical Marks
396    Greek Block
397    Cyrillic Block
398    Armenian Block
399    Hebrew Block
400    Arabic Block
401    Syriac Block
402    Thaana Block
403    Devanagari Block
404    Bengali Block
405    Gurmukhi Block
406    Gujarati Block
407    Oriya Block
408    Tamil Block
409    Telugu Block
410    Kannada Block
411    Malayalam Block
412    Sinhala Block
413    Thai Block
414    Lao Block
415    Tibetan Block
416    Myanmar Block
417    Georgian Block
418    Hangul Jamo
419    Ethiopic Block
420    Cherokee Block
421    Unified Canadian Aboriginal Syllabics
422    Ogham Block
423    Runic Block
424    Khmer Block
425    Mongolian Block
426    Latin Extended Additional
427    Greek Extended
428    General Punctuation
429    Superscripts and Subscripts
430    Currency Symbols
431    Combining Marks for Symbols
432    Letterlike Symbols
433    Number Forms
434    Arrows
435    Mathematical Operators
436    Miscellaneous Technical
437    Control Pictures
438    Optical Character Recognition
439    Enclosed Alphanumerics
440    Box Drawing
441    Block Elements
442    Geometric Shapes
443    Miscellaneous Symbols
444    Dingbats
445    Braille Patterns
446    CJK Radicals Supplement
447    Kangxi Radicals
448    Ideographic Description Characters
449    CJK Symbols and Punctuation
450    Hiragana Block
451    Katakana Block
452    Bopomofo Block
453    Hangul Compatibility Jamo
454    Kanbun
455    Bopomofo Extended
456    Enclosed CJK Letters and Months
457    CJK Compatibility
458    CJK Unified Ideographs Extension A
459    CJK Unified Ideographs
460    Yi Syllables
461    Yi Radicals
462    Hangul Syllables
463    High Surrogates
464    High Private Use Surrogates
465    Low Surrogates
466    Private Use
467    CJK Compatibility Ideographs
468    Alphabetic Presentation Forms
469    Arabic Presentation Forms-A
470    Combining Half Marks
471    CJK Compatibility Forms
472    Small Form Variants
473    Arabic Presentation Forms-B
474    Specials
475    Halfwidth and Fullwidth Forms
476    Old Italic Block
477    Gothic Block
478    Deseret Block
479    Byzantine Musical Symbols
480    Musical Symbols
481    Mathematical Alphanumeric Symbols
482    CJK Unified Ideographs Extension B
483    CJK Compatibility Ideographs Supplement
484    Tags
485
486 =item *
487
488 The special pattern C<\X> match matches any extended Unicode sequence
489 (a "combining character sequence" in Standardese), where the first
490 character is a base character and subsequent characters are mark
491 characters that apply to the base character.  It is equivalent to
492 C<(?:\PM\pM*)>.
493
494 =item *
495
496 The C<tr///> operator translates characters instead of bytes.  Note
497 that the C<tr///CU> functionality has been removed, as the interface
498 was a mistake.  For similar functionality see pack('U0', ...) and
499 pack('C0', ...).
500
501 =item *
502
503 Case translation operators use the Unicode case translation tables
504 when provided character input.  Note that C<uc()> translates to
505 uppercase, while C<ucfirst> translates to titlecase (for languages
506 that make the distinction).  Naturally the corresponding backslash
507 sequences have the same semantics.
508
509 =item *
510
511 Most operators that deal with positions or lengths in the string will
512 automatically switch to using character positions, including
513 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
514 C<sprintf()>, C<write()>, and C<length()>.  Operators that
515 specifically don't switch include C<vec()>, C<pack()>, and
516 C<unpack()>.  Operators that really don't care include C<chomp()>, as
517 well as any other operator that treats a string as a bucket of bits,
518 such as C<sort()>, and the operators dealing with filenames.
519
520 =item *
521
522 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
523 since they're often used for byte-oriented formats.  (Again, think
524 "C<char>" in the C language.)  However, there is a new "C<U>" specifier
525 that will convert between UTF-8 characters and integers.  (It works
526 outside of the utf8 pragma too.)
527
528 =item *
529
530 The C<chr()> and C<ord()> functions work on characters.  This is like
531 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
532 C<unpack("C")>.  In fact, the latter are how you now emulate
533 byte-oriented C<chr()> and C<ord()> for Unicode strings.
534 (Note that this reveals the internal UTF-8 encoding of strings and
535 you are not supposed to do that unless you know what you are doing.)
536
537 =item *
538
539 The bit string operators C<& | ^ ~> can operate on character data.
540 However, for backward compatibility reasons (bit string operations
541 when the characters all are less than 256 in ordinal value) one should
542 not mix C<~> (the bit complement) and characters both less than 256 and
543 equal or greater than 256.  Most importantly, the DeMorgan's laws
544 (C<~($x|$y) eq ~$x&~$y>, C<~($x&$y) eq ~$x|~$y>) won't hold.
545 Another way to look at this is that the complement cannot return
546 B<both> the 8-bit (byte) wide bit complement B<and> the full character
547 wide bit complement.
548
549 =item *
550
551 lc(), uc(), lcfirst(), and ucfirst() work only for some of the
552 simplest cases, where the mapping goes from a single Unicode character
553 to another single Unicode character, and where the mapping does not
554 depend on surrounding characters, or on locales.  More complex cases,
555 where for example one character maps into several, are not yet
556 implemented.  See the Unicode Technical Report #21, Case Mappings,
557 for more details.  The Unicode::UCD module (part of Perl since 5.8.0)
558 casespec() and casefold() interfaces supply information about the more
559 complex cases.
560
561 =item *
562
563 And finally, C<scalar reverse()> reverses by character rather than by byte.
564
565 =back
566
567 =head2 Character encodings for input and output
568
569 See L<Encode>.
570
571 =head1 CAVEATS
572
573 As of yet, there is no method for automatically coercing input and
574 output to some encoding other than UTF-8 or UTF-EBCDIC.  This is planned 
575 in the near future, however.
576
577 Whether an arbitrary piece of data will be treated as "characters" or
578 "bytes" by internal operations cannot be divined at the current time.
579
580 Use of locales with utf8 may lead to odd results.  Currently there is
581 some attempt to apply 8-bit locale info to characters in the range
582 0..255, but this is demonstrably incorrect for locales that use
583 characters above that range (when mapped into Unicode).  It will also
584 tend to run slower.  Avoidance of locales is strongly encouraged.
585
586 =head1 UNICODE REGULAR EXPRESSION SUPPORT LEVEL
587
588 The following list of Unicode regular expression support describes
589 feature by feature the Unicode support implemented in Perl as of Perl
590 5.8.0.  The "Level N" and the section numbers refer to the Unicode
591 Technical Report 18, "Unicode Regular Expression Guidelines".
592
593 =over 4
594
595 =item *
596
597 Level 1 - Basic Unicode Support
598
599         2.1 Hex Notation                        - done          [1]
600                 Named Notation                  - done          [2]
601         2.2 Categories                          - done          [3][4]
602         2.3 Subtraction                         - MISSING       [5][6]
603         2.4 Simple Word Boundaries              - done          [7]
604         2.5 Simple Loose Matches                - MISSING       [8]
605         2.6 End of Line                         - MISSING       [9][10]
606
607         [ 1] \x{...}
608         [ 2] \N{...}
609         [ 3] . \p{Is...} \P{Is...}
610         [ 4] now scripts (see UTR#24 Script Names) in  addition to blocks
611         [ 5] have negation
612         [ 6] can use look-ahead to emulate subtracion
613         [ 7] include Letters in word characters
614         [ 8] see UTR#21 Case Mappings
615         [ 9] see UTR#13 Unicode Newline Guidelines
616         [10] should do ^ and $ also on \x{2028} and \x{2029}
617
618 =item *
619
620 Level 2 - Extended Unicode Support
621
622         3.1 Surrogates                          - MISSING
623         3.2 Canonical Equivalents               - MISSING       [11][12]
624         3.3 Locale-Independent Graphemes        - MISSING       [13]
625         3.4 Locale-Independent Words            - MISSING       [14]
626         3.5 Locale-Independent Loose Matches    - MISSING       [15]
627
628         [11] see UTR#15 Unicode Normalization
629         [12] have Unicode::Normalize but not integrated to regexes
630         [13] have \X but at this level . should equal that
631         [14] need three classes, not just \w and \W
632         [15] see UTR#21 Case Mappings
633
634 =item *
635
636 Level 3 - Locale-Sensitive Support
637
638         4.1 Locale-Dependent Categories         - MISSING
639         4.2 Locale-Dependent Graphemes          - MISSING       [16][17]
640         4.3 Locale-Dependent Words              - MISSING
641         4.4 Locale-Dependent Loose Matches      - MISSING
642         4.5 Locale-Dependent Ranges             - MISSING
643
644         [16] see UTR#10 Unicode Collation Algorithms
645         [17] have Unicode::Collate but not integrated to regexes
646
647 =back
648
649 =head1 SEE ALSO
650
651 L<bytes>, L<utf8>, L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">
652
653 =cut