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