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