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