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