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