3 perlunicode - Unicode support in Perl
7 =head2 Important Caveats
9 WARNING: While the implementation of Unicode support in Perl is now fairly
10 complete it is still evolving to some extent.
12 In particular the way Unicode is handled on EBCDIC platforms is still
13 rather experimental. On such a platform references to UTF-8 encoding
14 in this document and elsewhere should be read as meaning UTF-EBCDIC as
15 specified in Unicode Technical Report 16 unless ASCII vs EBCDIC issues
16 are specifically discussed. There is no C<utfebcdic> pragma or
17 ":utfebcdic" layer, rather "utf8" and ":utf8" are re-used to mean
18 platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic> for
19 more discussion of the issues.
21 The following areas are still under development.
25 =item Input and Output Disciplines
27 A filehandle can be marked as containing perl's internal Unicode
28 encoding (UTF-8 or UTF-EBCDIC) by opening it with the ":utf8" layer.
29 Other encodings can be converted to perl's encoding on input, or from
30 perl's encoding on output by use of the ":encoding()" layer. There is
31 not yet a clean way to mark the Perl source itself as being in an
34 =item Regular Expressions
36 The regular expression compiler does now attempt to produce
37 polymorphic opcodes. That is the pattern should now adapt to the data
38 and automatically switch to the Unicode character scheme when
39 presented with Unicode data, or a traditional byte scheme when
40 presented with byte data. The implementation is still new and
41 (particularly on EBCDIC platforms) may need further work.
43 =item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts
45 The C<utf8> pragma implements the tables used for Unicode support.
46 These tables are automatically loaded on demand, so the C<utf8> pragma
47 need not normally be used.
49 However, as a compatibility measure, this pragma must be explicitly
50 used to enable recognition of UTF-8 in the Perl scripts themselves on
51 ASCII based machines or recognize UTF-EBCDIC on EBCDIC based machines.
52 B<This should be the only place where an explicit C<use utf8> is needed>.
56 =head2 Byte and Character semantics
58 Beginning with version 5.6, Perl uses logically wide characters to
59 represent strings internally. This internal representation of strings
60 uses either the UTF-8 or the UTF-EBCDIC encoding.
62 In future, Perl-level operations can be expected to work with
63 characters rather than bytes, in general.
65 However, as strictly an interim compatibility measure, Perl aims to
66 provide a safe migration path from byte semantics to character
67 semantics for programs. For operations where Perl can unambiguously
68 decide that the input data is characters, Perl now switches to
69 character semantics. For operations where this determination cannot
70 be made without additional information from the user, Perl decides in
71 favor of compatibility, and chooses to use byte semantics.
73 This behavior preserves compatibility with earlier versions of Perl,
74 which allowed byte semantics in Perl operations, but only as long as
75 none of the program's inputs are marked as being as source of Unicode
76 character data. Such data may come from filehandles, from calls to
77 external programs, from information provided by the system (such as %ENV),
78 or from literals and constants in the source text.
80 If the C<-C> command line switch is used, (or the
81 ${^WIDE_SYSTEM_CALLS} global flag is set to C<1>), all system calls
82 will use the corresponding wide character APIs. Note that this is
83 currently only implemented on Windows since other platforms API
84 standard on this area.
86 Regardless of the above, the C<bytes> pragma can always be used to
87 force byte semantics in a particular lexical scope. See L<bytes>.
89 The C<utf8> pragma is primarily a compatibility device that enables
90 recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
91 It may also be used for enabling some of the more experimental Unicode
92 support features. Note that this pragma is only required until a
93 future version of Perl in which character semantics will become the
94 default. This pragma may then become a no-op. See L<utf8>.
96 Unless mentioned otherwise, Perl operators will use character semantics
97 when they are dealing with Unicode data, and byte semantics otherwise.
98 Thus, character semantics for these operations apply transparently; if
99 the input data came from a Unicode source (for example, by adding a
100 character encoding discipline to the filehandle whence it came, or a
101 literal UTF-8 string constant in the program), character semantics
102 apply; otherwise, byte semantics are in effect. To force byte semantics
103 on Unicode data, the C<bytes> pragma should be used.
105 Under character semantics, many operations that formerly operated on
106 bytes change to operating on characters. For ASCII data this makes no
107 difference, because UTF-8 stores ASCII in single bytes, but for any
108 character greater than C<chr(127)>, the character B<may> be stored in
109 a sequence of two or more bytes, all of which have the high bit set.
111 For C1 controls or Latin 1 characters on an EBCDIC platform the
112 character may be stored in a UTF-EBCDIC multi byte sequence. But by
113 and large, the user need not worry about this, because Perl hides it
114 from the user. A character in Perl is logically just a number ranging
115 from 0 to 2**32 or so. Larger characters encode to longer sequences
116 of bytes internally, but again, this is just an internal detail which
117 is hidden at the Perl level.
119 =head2 Effects of character semantics
121 Character semantics have the following effects:
127 Strings and patterns may contain characters that have an ordinal value
130 Presuming you use a Unicode editor to edit your program, such
131 characters will typically occur directly within the literal strings as
132 UTF-8 (or UTF-EBCDIC on EBCDIC platforms) characters, but you can also
133 specify a particular character with an extension of the C<\x>
134 notation. UTF-X characters are specified by putting the hexadecimal
135 code within curlies after the C<\x>. For instance, a Unicode smiley
140 Identifiers within the Perl script may contain Unicode alphanumeric
141 characters, including ideographs. (You are currently on your own when
142 it comes to using the canonical forms of characters--Perl doesn't
143 (yet) attempt to canonicalize variable names for you.)
147 Regular expressions match characters instead of bytes. For instance,
148 "." matches a character instead of a byte. (However, the C<\C> pattern
149 is provided to force a match a single byte ("C<char>" in C, hence C<\C>).)
153 Character classes in regular expressions match characters instead of
154 bytes, and match against the character properties specified in the
155 Unicode properties database. So C<\w> can be used to match an
156 ideograph, for instance.
160 Named Unicode properties and block ranges make be used as character
161 classes via the new C<\p{}> (matches property) and C<\P{}> (doesn't
162 match property) constructs. For instance, C<\p{Lu}> matches any
163 character with the Unicode uppercase property, while C<\p{M}> matches
164 any mark character. Single letter properties may omit the brackets,
165 so that can be written C<\pM> also. Many predefined character classes
166 are available, such as C<\p{IsMirrored}> and C<\p{InTibetan}>. The
167 names of the C<In> classes are the official Unicode script and block
168 names but with all non-alphanumeric characters removed, for example
169 the block name C<"Latin-1 Supplement"> becomes C<\p{InLatin1Supplement}>.
171 Here is the list as of Unicode 3.1.0 (the two-letter classes) and
172 as defined by Perl (the one-letter classes) (in Unicode materials
173 what Perl calls C<L> is often called C<L&>):
183 Mc Mark, Spacing Combining
186 Nd Number, Decimal Digit
190 Pc Punctuation, Connector
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
207 Zp Separator, Paragraph
212 Co Other, Private Use
213 Cn Other, Not Assigned (Unicode defines no Cn characters)
215 Additionally, because scripts differ in their directionality
216 (for example Hebrew is written right to left), all characters
217 have their directionality defined:
220 BidiLRE Left-to-Right Embedding
221 BidiLRO Left-to-Right Override
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
231 BidiCS Common Number Separator
232 BidiNSM Non-Spacing Mark
233 BidiBN Boundary Neutral
234 BidiB Paragraph Separator
235 BidiS Segment Separator
237 BidiON Other Neutrals
241 The 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}>:
287 In addition to B<scripts>, Unicode also defines B<blocks> of
288 characters. The difference between scripts and blocks is that the
289 former concept is closer to natural languages, while the latter
290 concept is more an artificial grouping based on groups of 256 Unicode
291 characters. For example, the C<Latin> script contains letters from
292 many blocks, but it does not contain all the characters from those
293 blocks, it does not for example contain digits.
295 For more about scripts see the UTR #24:
296 http://www.unicode.org/unicode/reports/tr24/
297 For more about blocks see
298 http://www.unicode.org/Public/UNIDATA/Blocks.txt
300 Because there are overlaps in naming (there are, for example, both
301 a script called C<Katakana> and a block called C<Katakana>, the block
302 version has C<Block> appended to its name, C<\p{InKatakanaBlock}>.
304 Notice that this definition was introduced in Perl 5.8.0: in Perl
305 5.6.0 only the blocks were used; in Perl 5.8.0 scripts became the
306 preferential character class definition; this meant that the
307 definitions of some character classes changed (the ones in the
308 below list that have the C<Block> appended).
315 SpacingModifierLetters
316 CombiningDiacriticalMarks
342 UnifiedCanadianAboriginalSyllabics
347 LatinExtendedAdditional
350 SuperscriptsandSubscripts
352 CombiningMarksforSymbols
356 MathematicalOperators
357 MiscellaneousTechnical
359 OpticalCharacterRecognition
360 EnclosedAlphanumerics
367 CJKRadicalsSupplement
369 IdeographicDescriptionCharacters
370 CJKSymbolsandPunctuation
374 HangulCompatibilityJamo
377 EnclosedCJKLettersandMonths
379 CJKUnifiedIdeographsExtensionA
385 HighPrivateUseSurrogates
388 CJKCompatibilityIdeographs
389 AlphabeticPresentationForms
390 ArabicPresentationFormsA
392 CJKCompatibilityForms
394 ArabicPresentationFormsB
396 HalfwidthandFullwidthForms
400 ByzantineMusicalSymbols
402 MathematicalAlphanumericSymbols
403 CJKUnifiedIdeographsExtensionB
404 CJKCompatibilityIdeographsSupplement
409 The special pattern C<\X> match matches any extended Unicode sequence
410 (a "combining character sequence" in Standardese), where the first
411 character is a base character and subsequent characters are mark
412 characters that apply to the base character. It is equivalent to
417 The C<tr///> operator translates characters instead of bytes. Note
418 that the C<tr///CU> functionality has been removed, as the interface
419 was a mistake. For similar functionality see pack('U0', ...) and
424 Case translation operators use the Unicode case translation tables
425 when provided character input. Note that C<uc()> translates to
426 uppercase, while C<ucfirst> translates to titlecase (for languages
427 that make the distinction). Naturally the corresponding backslash
428 sequences have the same semantics.
432 Most operators that deal with positions or lengths in the string will
433 automatically switch to using character positions, including
434 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
435 C<sprintf()>, C<write()>, and C<length()>. Operators that
436 specifically don't switch include C<vec()>, C<pack()>, and
437 C<unpack()>. Operators that really don't care include C<chomp()>, as
438 well as any other operator that treats a string as a bucket of bits,
439 such as C<sort()>, and the operators dealing with filenames.
443 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
444 since 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
446 that will convert between UTF-8 characters and integers. (It works
447 outside of the utf8 pragma too.)
451 The C<chr()> and C<ord()> functions work on characters. This is like
452 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
453 C<unpack("C")>. In fact, the latter are how you now emulate
454 byte-oriented C<chr()> and C<ord()> under utf8.
458 The bit string operators C<& | ^ ~> can operate on character data.
459 However, for backward compatibility reasons (bit string operations
460 when the characters all are less than 256 in ordinal value) one should
461 not mix C<~> (the bit complement) and characters both less than 256 and
462 equal 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.
464 Another way to look at this is that the complement cannot return
465 B<both> the 8-bit (byte) wide bit complement B<and> the full character
470 And finally, C<scalar reverse()> reverses by character rather than by byte.
474 =head2 Character encodings for input and output
480 As of yet, there is no method for automatically coercing input and
481 output to some encoding other than UTF-8 or UTF-EBCDIC. This is planned
482 in the near future, however.
484 Whether an arbitrary piece of data will be treated as "characters" or
485 "bytes" by internal operations cannot be divined at the current time.
487 Use of locales with utf8 may lead to odd results. Currently there is
488 some attempt to apply 8-bit locale info to characters in the range
489 0..255, but this is demonstrably incorrect for locales that use
490 characters above that range (when mapped into Unicode). It will also
491 tend to run slower. Avoidance of locales is strongly encouraged.
495 L<bytes>, L<utf8>, L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">