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