Commit | Line | Data |
---|---|---|
393fec97 GS |
1 | =head1 NAME |
2 | ||
3 | perlunicode - Unicode support in Perl | |
4 | ||
5 | =head1 DESCRIPTION | |
6 | ||
0a1f2d14 | 7 | =head2 Important Caveats |
21bad921 | 8 | |
376d9008 | 9 | Unicode support is an extensive requirement. While Perl does not |
c349b1b9 JH |
10 | implement the Unicode standard or the accompanying technical reports |
11 | from cover to cover, Perl does support many Unicode features. | |
21bad921 | 12 | |
2575c402 | 13 | People who want to learn to use Unicode in Perl, should probably read |
e4911a48 RS |
14 | L<the Perl Unicode tutorial, perlunitut|perlunitut>, before reading |
15 | this reference document. | |
2575c402 | 16 | |
13a2d996 | 17 | =over 4 |
21bad921 | 18 | |
fae2c0fb | 19 | =item Input and Output Layers |
21bad921 | 20 | |
376d9008 | 21 | Perl knows when a filehandle uses Perl's internal Unicode encodings |
1bfb14c4 JH |
22 | (UTF-8, or UTF-EBCDIC if in EBCDIC) if the filehandle is opened with |
23 | the ":utf8" layer. Other encodings can be converted to Perl's | |
24 | encoding on input or from Perl's encoding on output by use of the | |
25 | ":encoding(...)" layer. See L<open>. | |
c349b1b9 | 26 | |
2575c402 | 27 | To indicate that Perl source itself is in UTF-8, use C<use utf8;>. |
21bad921 GS |
28 | |
29 | =item Regular Expressions | |
30 | ||
c349b1b9 | 31 | The regular expression compiler produces polymorphic opcodes. That is, |
376d9008 | 32 | the pattern adapts to the data and automatically switches to the Unicode |
2575c402 JW |
33 | character scheme when presented with data that is internally encoded in |
34 | UTF-8 -- or instead uses a traditional byte scheme when presented with | |
35 | byte data. | |
21bad921 | 36 | |
ad0029c4 | 37 | =item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts |
21bad921 | 38 | |
376d9008 JB |
39 | As a compatibility measure, the C<use utf8> pragma must be explicitly |
40 | included to enable recognition of UTF-8 in the Perl scripts themselves | |
1bfb14c4 JH |
41 | (in string or regular expression literals, or in identifier names) on |
42 | ASCII-based machines or to recognize UTF-EBCDIC on EBCDIC-based | |
376d9008 | 43 | machines. B<These are the only times when an explicit C<use utf8> |
8f8cf39c | 44 | is needed.> See L<utf8>. |
21bad921 | 45 | |
7aa207d6 JH |
46 | =item BOM-marked scripts and UTF-16 scripts autodetected |
47 | ||
48 | If a Perl script begins marked with the Unicode BOM (UTF-16LE, UTF16-BE, | |
49 | or UTF-8), or if the script looks like non-BOM-marked UTF-16 of either | |
50 | endianness, Perl will correctly read in the script as Unicode. | |
51 | (BOMless UTF-8 cannot be effectively recognized or differentiated from | |
52 | ISO 8859-1 or other eight-bit encodings.) | |
53 | ||
990e18f7 AT |
54 | =item C<use encoding> needed to upgrade non-Latin-1 byte strings |
55 | ||
38a44b82 | 56 | By default, there is a fundamental asymmetry in Perl's Unicode model: |
990e18f7 AT |
57 | implicit upgrading from byte strings to Unicode strings assumes that |
58 | they were encoded in I<ISO 8859-1 (Latin-1)>, but Unicode strings are | |
59 | downgraded with UTF-8 encoding. This happens because the first 256 | |
51f494cc | 60 | codepoints in Unicode happens to agree with Latin-1. |
990e18f7 | 61 | |
990e18f7 AT |
62 | See L</"Byte and Character Semantics"> for more details. |
63 | ||
21bad921 GS |
64 | =back |
65 | ||
376d9008 | 66 | =head2 Byte and Character Semantics |
393fec97 | 67 | |
376d9008 | 68 | Beginning with version 5.6, Perl uses logically-wide characters to |
3e4dbfed | 69 | represent strings internally. |
393fec97 | 70 | |
376d9008 JB |
71 | In future, Perl-level operations will be expected to work with |
72 | characters rather than bytes. | |
393fec97 | 73 | |
376d9008 | 74 | However, as an interim compatibility measure, Perl aims to |
75daf61c JH |
75 | provide a safe migration path from byte semantics to character |
76 | semantics for programs. For operations where Perl can unambiguously | |
376d9008 | 77 | decide that the input data are characters, Perl switches to |
75daf61c JH |
78 | character semantics. For operations where this determination cannot |
79 | be made without additional information from the user, Perl decides in | |
376d9008 | 80 | favor of compatibility and chooses to use byte semantics. |
8cbd9a7a | 81 | |
51f494cc | 82 | Under byte semantics, when C<use locale> is in effect, Perl uses the |
2bbc8d55 SP |
83 | semantics associated with the current locale. Absent a C<use locale>, Perl |
84 | currently uses US-ASCII (or Basic Latin in Unicode terminology) byte semantics, | |
85 | meaning that characters whose ordinal numbers are in the range 128 - 255 are | |
86 | undefined except for their ordinal numbers. This means that none have case | |
87 | (upper and lower), nor are any a member of character classes, like C<[:alpha:]> | |
88 | or C<\w>. | |
89 | (But all do belong to the C<\W> class or the Perl regular expression extension | |
90 | C<[:^alpha:]>.) | |
91 | ||
8cbd9a7a | 92 | This behavior preserves compatibility with earlier versions of Perl, |
376d9008 JB |
93 | which allowed byte semantics in Perl operations only if |
94 | none of the program's inputs were marked as being as source of Unicode | |
8cbd9a7a GS |
95 | character data. Such data may come from filehandles, from calls to |
96 | external programs, from information provided by the system (such as %ENV), | |
21bad921 | 97 | or from literals and constants in the source text. |
8cbd9a7a | 98 | |
376d9008 JB |
99 | The C<bytes> pragma will always, regardless of platform, force byte |
100 | semantics in a particular lexical scope. See L<bytes>. | |
8cbd9a7a GS |
101 | |
102 | The C<utf8> pragma is primarily a compatibility device that enables | |
75daf61c | 103 | recognition of UTF-(8|EBCDIC) in literals encountered by the parser. |
376d9008 JB |
104 | Note that this pragma is only required while Perl defaults to byte |
105 | semantics; when character semantics become the default, this pragma | |
106 | may become a no-op. See L<utf8>. | |
107 | ||
108 | Unless explicitly stated, Perl operators use character semantics | |
109 | for Unicode data and byte semantics for non-Unicode data. | |
110 | The decision to use character semantics is made transparently. If | |
111 | input data comes from a Unicode source--for example, if a character | |
fae2c0fb | 112 | encoding layer is added to a filehandle or a literal Unicode |
376d9008 JB |
113 | string constant appears in a program--character semantics apply. |
114 | Otherwise, byte semantics are in effect. The C<bytes> pragma should | |
115 | be used to force byte semantics on Unicode data. | |
116 | ||
117 | If strings operating under byte semantics and strings with Unicode | |
51f494cc | 118 | character data are concatenated, the new string will have |
42bde815 | 119 | character semantics. This can cause surprises: See L</BUGS>, below |
7dedd01f | 120 | |
feda178f | 121 | Under character semantics, many operations that formerly operated on |
376d9008 | 122 | bytes now operate on characters. A character in Perl is |
feda178f | 123 | logically just a number ranging from 0 to 2**31 or so. Larger |
376d9008 JB |
124 | characters may encode into longer sequences of bytes internally, but |
125 | this internal detail is mostly hidden for Perl code. | |
126 | See L<perluniintro> for more. | |
393fec97 | 127 | |
376d9008 | 128 | =head2 Effects of Character Semantics |
393fec97 GS |
129 | |
130 | Character semantics have the following effects: | |
131 | ||
132 | =over 4 | |
133 | ||
134 | =item * | |
135 | ||
376d9008 | 136 | Strings--including hash keys--and regular expression patterns may |
574c8022 | 137 | contain characters that have an ordinal value larger than 255. |
393fec97 | 138 | |
2575c402 JW |
139 | If you use a Unicode editor to edit your program, Unicode characters may |
140 | occur directly within the literal strings in UTF-8 encoding, or UTF-16. | |
141 | (The former requires a BOM or C<use utf8>, the latter requires a BOM.) | |
3e4dbfed | 142 | |
2575c402 JW |
143 | Unicode characters can also be added to a string by using the C<\x{...}> |
144 | notation. The Unicode code for the desired character, in hexadecimal, | |
145 | should be placed in the braces. For instance, a smiley face is | |
2bbc8d55 | 146 | C<\x{263A}>. This encoding scheme works for all characters, but |
2575c402 JW |
147 | for characters under 0x100, note that Perl may use an 8 bit encoding |
148 | internally, for optimization and/or backward compatibility. | |
3e4dbfed JF |
149 | |
150 | Additionally, if you | |
574c8022 | 151 | |
3e4dbfed | 152 | use charnames ':full'; |
574c8022 | 153 | |
1bfb14c4 JH |
154 | you can use the C<\N{...}> notation and put the official Unicode |
155 | character name within the braces, such as C<\N{WHITE SMILING FACE}>. | |
376d9008 | 156 | |
393fec97 GS |
157 | =item * |
158 | ||
574c8022 JH |
159 | If an appropriate L<encoding> is specified, identifiers within the |
160 | Perl script may contain Unicode alphanumeric characters, including | |
376d9008 JB |
161 | ideographs. Perl does not currently attempt to canonicalize variable |
162 | names. | |
393fec97 | 163 | |
393fec97 GS |
164 | =item * |
165 | ||
1bfb14c4 | 166 | Regular expressions match characters instead of bytes. "." matches |
2575c402 | 167 | a character instead of a byte. |
393fec97 | 168 | |
393fec97 GS |
169 | =item * |
170 | ||
171 | Character classes in regular expressions match characters instead of | |
376d9008 | 172 | bytes and match against the character properties specified in the |
1bfb14c4 | 173 | Unicode properties database. C<\w> can be used to match a Japanese |
75daf61c | 174 | ideograph, for instance. |
393fec97 | 175 | |
393fec97 GS |
176 | =item * |
177 | ||
eb0cc9e3 | 178 | Named Unicode properties, scripts, and block ranges may be used like |
376d9008 | 179 | character classes via the C<\p{}> "matches property" construct and |
822502e5 TS |
180 | the C<\P{}> negation, "doesn't match property". |
181 | ||
2575c402 | 182 | See L</"Unicode Character Properties"> for more details. |
822502e5 TS |
183 | |
184 | You can define your own character properties and use them | |
185 | in the regular expression with the C<\p{}> or C<\P{}> construct. | |
186 | ||
187 | See L</"User-Defined Character Properties"> for more details. | |
188 | ||
189 | =item * | |
190 | ||
51f494cc KW |
191 | The special pattern C<\X> matches a logical character, an C<extended grapheme |
192 | cluster> in Standardese. In Unicode what appears to the user to be a single | |
193 | character, for example an accented C<G>, may in fact be composed of a sequence | |
194 | of characters, in this case a C<G> followed by an accent character. C<\X> | |
195 | will match the entire sequence. | |
822502e5 TS |
196 | |
197 | =item * | |
198 | ||
199 | The C<tr///> operator translates characters instead of bytes. Note | |
200 | that the C<tr///CU> functionality has been removed. For similar | |
201 | functionality see pack('U0', ...) and pack('C0', ...). | |
202 | ||
203 | =item * | |
204 | ||
205 | Case translation operators use the Unicode case translation tables | |
206 | when character input is provided. Note that C<uc()>, or C<\U> in | |
207 | interpolated strings, translates to uppercase, while C<ucfirst>, | |
208 | or C<\u> in interpolated strings, translates to titlecase in languages | |
209 | that make the distinction. | |
210 | ||
211 | =item * | |
212 | ||
213 | Most operators that deal with positions or lengths in a string will | |
214 | automatically switch to using character positions, including | |
215 | C<chop()>, C<chomp()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>, | |
216 | C<sprintf()>, C<write()>, and C<length()>. An operator that | |
51f494cc KW |
217 | specifically does not switch is C<vec()>. Operators that really don't |
218 | care include operators that treat strings as a bucket of bits such as | |
822502e5 TS |
219 | C<sort()>, and operators dealing with filenames. |
220 | ||
221 | =item * | |
222 | ||
51f494cc | 223 | The C<pack()>/C<unpack()> letter C<C> does I<not> change, since it is often |
822502e5 TS |
224 | used for byte-oriented formats. Again, think C<char> in the C language. |
225 | ||
226 | There is a new C<U> specifier that converts between Unicode characters | |
227 | and code points. There is also a C<W> specifier that is the equivalent of | |
228 | C<chr>/C<ord> and properly handles character values even if they are above 255. | |
229 | ||
230 | =item * | |
231 | ||
232 | The C<chr()> and C<ord()> functions work on characters, similar to | |
233 | C<pack("W")> and C<unpack("W")>, I<not> C<pack("C")> and | |
234 | C<unpack("C")>. C<pack("C")> and C<unpack("C")> are methods for | |
235 | emulating byte-oriented C<chr()> and C<ord()> on Unicode strings. | |
236 | While these methods reveal the internal encoding of Unicode strings, | |
237 | that is not something one normally needs to care about at all. | |
238 | ||
239 | =item * | |
240 | ||
241 | The bit string operators, C<& | ^ ~>, can operate on character data. | |
242 | However, for backward compatibility, such as when using bit string | |
243 | operations when characters are all less than 256 in ordinal value, one | |
244 | should not use C<~> (the bit complement) with characters of both | |
245 | values less than 256 and values greater than 256. Most importantly, | |
246 | DeMorgan's laws (C<~($x|$y) eq ~$x&~$y> and C<~($x&$y) eq ~$x|~$y>) | |
247 | will not hold. The reason for this mathematical I<faux pas> is that | |
248 | the complement cannot return B<both> the 8-bit (byte-wide) bit | |
249 | complement B<and> the full character-wide bit complement. | |
250 | ||
251 | =item * | |
252 | ||
253 | lc(), uc(), lcfirst(), and ucfirst() work for the following cases: | |
254 | ||
255 | =over 8 | |
256 | ||
257 | =item * | |
258 | ||
259 | the case mapping is from a single Unicode character to another | |
260 | single Unicode character, or | |
261 | ||
262 | =item * | |
263 | ||
264 | the case mapping is from a single Unicode character to more | |
265 | than one Unicode character. | |
266 | ||
267 | =back | |
268 | ||
269 | Things to do with locales (Lithuanian, Turkish, Azeri) do B<not> work | |
270 | since Perl does not understand the concept of Unicode locales. | |
271 | ||
272 | See the Unicode Technical Report #21, Case Mappings, for more details. | |
273 | ||
274 | But you can also define your own mappings to be used in the lc(), | |
275 | lcfirst(), uc(), and ucfirst() (or their string-inlined versions). | |
276 | ||
277 | See L</"User-Defined Case Mappings"> for more details. | |
278 | ||
279 | =back | |
280 | ||
281 | =over 4 | |
282 | ||
283 | =item * | |
284 | ||
285 | And finally, C<scalar reverse()> reverses by character rather than by byte. | |
286 | ||
287 | =back | |
288 | ||
289 | =head2 Unicode Character Properties | |
290 | ||
51f494cc KW |
291 | Most Unicode character properties are accessible by using regular expressions. |
292 | They are used like character classes via the C<\p{}> "matches property" | |
293 | construct and the C<\P{}> negation, "doesn't match property". | |
294 | ||
295 | For instance, C<\p{Uppercase}> matches any character with the Unicode | |
296 | "Uppercase" property, while C<\p{L}> matches any character with a | |
297 | General_Category of "L" (letter) property. Brackets are not | |
298 | required for single letter properties, so C<\p{L}> is equivalent to C<\pL>. | |
299 | ||
300 | More formally, C<\p{Uppercase}> matches any character whose Uppercase property | |
301 | value is True, and C<\P{Uppercase}> matches any character whose Uppercase | |
302 | property value is False, and they could have been written as | |
303 | C<\p{Uppercase=True}> and C<\p{Uppercase=False}>, respectively | |
304 | ||
305 | This formality is needed when properties are not binary, that is if they can | |
306 | take on more values than just True and False. For example, the Bidi_Class (see | |
307 | L</"Bidirectional Character Types"> below), can take on a number of different | |
308 | values, such as Left, Right, Whitespace, and others. To match these, one needs | |
309 | to specify the property name (Bidi_Class), and the value being matched with | |
310 | (Left, Right, etc.). This is done, as in the examples above, by having the two | |
311 | components separated by an equal sign (or interchangeably, a colon), like | |
312 | C<\p{Bidi_Class: Left}>. | |
313 | ||
314 | All Unicode-defined character properties may be written in these compound forms | |
315 | of C<\p{property=value}> or C<\p{property:value}>, but Perl provides some | |
316 | additional properties that are written only in the single form, as well as | |
317 | single-form short-cuts for all binary properties and certain others described | |
318 | below, in which you may omit the property name and the equals or colon | |
319 | separator. | |
320 | ||
321 | Most Unicode character properties have at least two synonyms (or aliases if you | |
322 | prefer), a short one that is easier to type, and a longer one which is more | |
323 | descriptive and hence it is easier to understand what it means. Thus the "L" | |
324 | and "Letter" above are equivalent and can be used interchangeably. Likewise, | |
325 | "Upper" is a synonym for "Uppercase", and we could have written | |
326 | C<\p{Uppercase}> equivalently as C<\p{Upper}>. Also, there are typically | |
327 | various synonyms for the values the property can be. For binary properties, | |
328 | "True" has 3 synonyms: "T", "Yes", and "Y"; and "False has correspondingly "F", | |
329 | "No", and "N". But be careful. A short form of a value for one property may | |
330 | not mean the same thing as the same name for another. Thus, for the | |
331 | General_Category property, "L" means "Letter", but for the Bidi_Class property, | |
332 | "L" means "Left". A complete list of properties and synonyms is in | |
333 | L<perluniprops>. | |
334 | ||
335 | Upper/lower case differences in the property names and values are irrelevant, | |
336 | thus C<\p{Upper}> means the same thing as C<\p{upper}> or even C<\p{UpPeR}>. | |
337 | Similarly, you can add or subtract underscores anywhere in the middle of a | |
338 | word, so that these are also equivalent to C<\p{U_p_p_e_r}>. And white space | |
339 | is irrelevant adjacent to non-word characters, such as the braces and the equals | |
340 | or colon separators so C<\p{ Upper }> and C<\p{ Upper_case : Y }> are | |
341 | equivalent to these as well. In fact, in most cases, white space and even | |
342 | hyphens can be added or deleted anywhere. So even C<\p{ Up-per case = Yes}> is | |
343 | equivalent. All this is called "loose-matching" by Unicode. The few places | |
344 | where stricter matching is employed is in the middle of numbers, and the Perl | |
345 | extension properties that begin or end with an underscore. Stricter matching | |
346 | cares about white space (except adjacent to the non-word characters) and | |
347 | hyphens, and non-interior underscores. | |
4193bef7 | 348 | |
376d9008 JB |
349 | You can also use negation in both C<\p{}> and C<\P{}> by introducing a caret |
350 | (^) between the first brace and the property name: C<\p{^Tamil}> is | |
eb0cc9e3 | 351 | equal to C<\P{Tamil}>. |
4193bef7 | 352 | |
51f494cc | 353 | =head3 B<General_Category> |
14bb0a9a | 354 | |
51f494cc KW |
355 | Every Unicode character is assigned a general category, which is the "most |
356 | usual categorization of a character" (from | |
357 | L<http://www.unicode.org/reports/tr44>). | |
822502e5 | 358 | |
51f494cc KW |
359 | The compound way of writing these is like C<{\p{General_Category=Number}> |
360 | (short, C<\p{gc:n}>). But Perl furnishes shortcuts in which everything up | |
361 | through the equal or colon separator is omitted. So you can instead just write | |
362 | C<\pN>. | |
822502e5 | 363 | |
51f494cc | 364 | Here are the short and long forms of the General Category properties: |
393fec97 | 365 | |
d73e5302 JH |
366 | Short Long |
367 | ||
368 | L Letter | |
51f494cc KW |
369 | LC, L& Cased_Letter (that is: [\p{Ll}\p{Lu}\p{Lt}]) |
370 | Lu Uppercase_Letter | |
371 | Ll Lowercase_Letter | |
372 | Lt Titlecase_Letter | |
373 | Lm Modifier_Letter | |
374 | Lo Other_Letter | |
d73e5302 JH |
375 | |
376 | M Mark | |
51f494cc KW |
377 | Mn Nonspacing_Mark |
378 | Mc Spacing_Mark | |
379 | Me Enclosing_Mark | |
d73e5302 JH |
380 | |
381 | N Number | |
51f494cc KW |
382 | Nd Decimal_Number (also Digit) |
383 | Nl Letter_Number | |
384 | No Other_Number | |
385 | ||
386 | P Punctuation (also Punct) | |
387 | Pc Connector_Punctuation | |
388 | Pd Dash_Punctuation | |
389 | Ps Open_Punctuation | |
390 | Pe Close_Punctuation | |
391 | Pi Initial_Punctuation | |
d73e5302 | 392 | (may behave like Ps or Pe depending on usage) |
51f494cc | 393 | Pf Final_Punctuation |
d73e5302 | 394 | (may behave like Ps or Pe depending on usage) |
51f494cc | 395 | Po Other_Punctuation |
d73e5302 JH |
396 | |
397 | S Symbol | |
51f494cc KW |
398 | Sm Math_Symbol |
399 | Sc Currency_Symbol | |
400 | Sk Modifier_Symbol | |
401 | So Other_Symbol | |
d73e5302 JH |
402 | |
403 | Z Separator | |
51f494cc KW |
404 | Zs Space_Separator |
405 | Zl Line_Separator | |
406 | Zp Paragraph_Separator | |
d73e5302 JH |
407 | |
408 | C Other | |
51f494cc | 409 | Cc Control (also Cntrl) |
e150c829 | 410 | Cf Format |
eb0cc9e3 | 411 | Cs Surrogate (not usable) |
51f494cc | 412 | Co Private_Use |
e150c829 | 413 | Cn Unassigned |
1ac13f9a | 414 | |
376d9008 | 415 | Single-letter properties match all characters in any of the |
3e4dbfed | 416 | two-letter sub-properties starting with the same letter. |
12ac2576 JP |
417 | C<LC> and C<L&> are special cases, which are aliases for the set of |
418 | C<Ll>, C<Lu>, and C<Lt>. | |
32293815 | 419 | |
eb0cc9e3 | 420 | Because Perl hides the need for the user to understand the internal |
1bfb14c4 JH |
421 | representation of Unicode characters, there is no need to implement |
422 | the somewhat messy concept of surrogates. C<Cs> is therefore not | |
eb0cc9e3 | 423 | supported. |
d73e5302 | 424 | |
51f494cc | 425 | =head3 B<Bidirectional Character Types> |
822502e5 | 426 | |
376d9008 | 427 | Because scripts differ in their directionality--Hebrew is |
12ac2576 | 428 | written right to left, for example--Unicode supplies these properties in |
51f494cc | 429 | the Bidi_Class class: |
32293815 | 430 | |
eb0cc9e3 | 431 | Property Meaning |
92e830a9 | 432 | |
12ac2576 JP |
433 | L Left-to-Right |
434 | LRE Left-to-Right Embedding | |
435 | LRO Left-to-Right Override | |
436 | R Right-to-Left | |
51f494cc | 437 | AL Arabic Letter |
12ac2576 JP |
438 | RLE Right-to-Left Embedding |
439 | RLO Right-to-Left Override | |
440 | PDF Pop Directional Format | |
441 | EN European Number | |
51f494cc KW |
442 | ES European Separator |
443 | ET European Terminator | |
12ac2576 | 444 | AN Arabic Number |
51f494cc | 445 | CS Common Separator |
12ac2576 JP |
446 | NSM Non-Spacing Mark |
447 | BN Boundary Neutral | |
448 | B Paragraph Separator | |
449 | S Segment Separator | |
450 | WS Whitespace | |
451 | ON Other Neutrals | |
452 | ||
51f494cc KW |
453 | This property is always written in the compound form. |
454 | For example, C<\p{Bidi_Class:R}> matches characters that are normally | |
eb0cc9e3 JH |
455 | written right to left. |
456 | ||
51f494cc KW |
457 | =head3 B<Scripts> |
458 | ||
459 | The world's languages are written in a number of scripts. This sentence is | |
460 | written in Latin, while Russian is written in Cyrllic, and Greek is written in, | |
461 | well, Greek; Japanese mainly in Hiragana or Katakana. There are many more. | |
462 | ||
463 | The Unicode Script property gives what script a given character is in, | |
464 | and can be matched with the compound form like C<\p{Script=Hebrew}> (short: | |
465 | C<\p{sc=hebr}>). Perl furnishes shortcuts for all script names. You can omit | |
466 | everything up through the equals (or colon), and simply write C<\p{Latin}> or | |
467 | C<\P{Cyrillic}>. | |
468 | ||
469 | A complete list of scripts and their shortcuts is in L<perluniprops>. | |
470 | ||
471 | =head3 B<Extended property classes> | |
472 | ||
473 | There are many more property classes than the basic ones described here, | |
474 | including some Perl extensions. | |
475 | A complete list is in L<perluniprops>. | |
476 | The extensions are more fully described in L<perlrecharclass> | |
477 | ||
478 | =head3 B<Use of "Is" Prefix> | |
822502e5 | 479 | |
1bfb14c4 | 480 | For backward compatibility (with Perl 5.6), all properties mentioned |
51f494cc KW |
481 | so far may have C<Is> or C<Is_> prepended to their name, so C<\P{Is_Lu}>, for |
482 | example, is equal to C<\P{Lu}>, and C<\p{IsScript:Arabic}> is equal to | |
483 | C<\p{Arabic}>. | |
eb0cc9e3 | 484 | |
51f494cc | 485 | =head3 B<Blocks> |
2796c109 | 486 | |
1bfb14c4 JH |
487 | In addition to B<scripts>, Unicode also defines B<blocks> of |
488 | characters. The difference between scripts and blocks is that the | |
489 | concept of scripts is closer to natural languages, while the concept | |
51f494cc KW |
490 | of blocks is more of an artificial grouping based on groups of Unicode |
491 | characters with consecutive ordinal values. For example, the C<Basic Latin> | |
492 | block is all characters whose ordinals are between 0 and 127, inclusive, in | |
493 | other words, the ASCII characters. The C<Latin> script contains some letters | |
494 | from this block as well as several more, like C<Latin-1 Supplement>, | |
495 | C<Latin Extended-A>, I<etc.>, but it does not contain all the characters from | |
496 | those blocks. It does not, for example, contain digits, because digits are | |
497 | shared across many scripts. Digits and similar groups, like punctuation, are in | |
498 | the script called C<Common>. There is also a script called C<Inherited> for | |
499 | characters that modify other characters, and inherit the script value of the | |
500 | controlling character. | |
501 | ||
502 | For more about scripts versus blocks, see UAX#24 "Unicode Script Property": | |
503 | L<http://www.unicode.org/reports/tr24> | |
504 | ||
505 | The Script property is likely to be the one you want to use when processing | |
506 | natural language; the Block property may be useful in working with the nuts and | |
507 | bolts of Unicode. | |
508 | ||
509 | Block names are matched in the compound form, like C<\p{Block: Arrows}> or | |
510 | C<\p{Blk=Hebrew}>. Unlike most other properties only a few block names have a | |
511 | Unicode-defined short name. But Perl does provide a (slight) shortcut: You | |
512 | can say, for example C<\p{In_Arrows}> or C<\p{In_Hebrew}>. For backwards | |
513 | compatibility, the C<In> prefix may be omitted if there is no naming conflict | |
514 | with a script or any other property, and you can even use an C<Is> prefix | |
515 | instead in those cases. But it is not a good idea to do this, for a couple | |
516 | reasons: | |
517 | ||
518 | =over 4 | |
519 | ||
520 | =item 1 | |
521 | ||
522 | It is confusing. There are many naming conflicts, and you may forget some. | |
523 | For example, \p{Hebrew} means the I<script> Hebrew, and NOT the I<block> | |
524 | Hebrew. But would you remember that 6 months from now? | |
525 | ||
526 | =item 2 | |
527 | ||
528 | It is unstable. A new version of Unicode may pre-empt the current meaning by | |
529 | creating a property with the same name. There was a time in very early Unicode | |
530 | releases when \p{Hebrew} would have matched the I<block> Hebrew; now it | |
531 | doesn't. | |
32293815 | 532 | |
393fec97 GS |
533 | =back |
534 | ||
51f494cc KW |
535 | Some people just prefer to always use C<\p{Block: foo}> and C<\p{Script: bar}> |
536 | instead of the shortcuts, for clarity, and because they can't remember the | |
537 | difference between 'In' and 'Is' anyway (or aren't confident that those who | |
538 | eventually will read their code will know). | |
539 | ||
540 | A complete list of blocks and their shortcuts is in L<perluniprops>. | |
541 | ||
376d9008 | 542 | =head2 User-Defined Character Properties |
491fd90a | 543 | |
51f494cc KW |
544 | You can define your own binary character properties by defining subroutines |
545 | whose names begin with "In" or "Is". The subroutines can be defined in any | |
546 | package. The user-defined properties can be used in the regular expression | |
547 | C<\p> and C<\P> constructs; if you are using a user-defined property from a | |
548 | package other than the one you are in, you must specify its package in the | |
549 | C<\p> or C<\P> construct. | |
bac0b425 | 550 | |
51f494cc | 551 | # assuming property Is_Foreign defined in Lang:: |
bac0b425 JP |
552 | package main; # property package name required |
553 | if ($txt =~ /\p{Lang::IsForeign}+/) { ... } | |
554 | ||
555 | package Lang; # property package name not required | |
556 | if ($txt =~ /\p{IsForeign}+/) { ... } | |
557 | ||
558 | ||
559 | Note that the effect is compile-time and immutable once defined. | |
491fd90a | 560 | |
376d9008 JB |
561 | The subroutines must return a specially-formatted string, with one |
562 | or more newline-separated lines. Each line must be one of the following: | |
491fd90a JH |
563 | |
564 | =over 4 | |
565 | ||
566 | =item * | |
567 | ||
510254c9 A |
568 | A single hexadecimal number denoting a Unicode code point to include. |
569 | ||
570 | =item * | |
571 | ||
99a6b1f0 | 572 | Two hexadecimal numbers separated by horizontal whitespace (space or |
376d9008 | 573 | tabular characters) denoting a range of Unicode code points to include. |
491fd90a JH |
574 | |
575 | =item * | |
576 | ||
376d9008 | 577 | Something to include, prefixed by "+": a built-in character |
bac0b425 JP |
578 | property (prefixed by "utf8::") or a user-defined character property, |
579 | to represent all the characters in that property; two hexadecimal code | |
580 | points for a range; or a single hexadecimal code point. | |
491fd90a JH |
581 | |
582 | =item * | |
583 | ||
376d9008 | 584 | Something to exclude, prefixed by "-": an existing character |
bac0b425 JP |
585 | property (prefixed by "utf8::") or a user-defined character property, |
586 | to represent all the characters in that property; two hexadecimal code | |
587 | points for a range; or a single hexadecimal code point. | |
491fd90a JH |
588 | |
589 | =item * | |
590 | ||
376d9008 | 591 | Something to negate, prefixed "!": an existing character |
bac0b425 JP |
592 | property (prefixed by "utf8::") or a user-defined character property, |
593 | to represent all the characters in that property; two hexadecimal code | |
594 | points for a range; or a single hexadecimal code point. | |
595 | ||
596 | =item * | |
597 | ||
598 | Something to intersect with, prefixed by "&": an existing character | |
599 | property (prefixed by "utf8::") or a user-defined character property, | |
600 | for all the characters except the characters in the property; two | |
601 | hexadecimal code points for a range; or a single hexadecimal code point. | |
491fd90a JH |
602 | |
603 | =back | |
604 | ||
605 | For example, to define a property that covers both the Japanese | |
606 | syllabaries (hiragana and katakana), you can define | |
607 | ||
608 | sub InKana { | |
d5822f25 A |
609 | return <<END; |
610 | 3040\t309F | |
611 | 30A0\t30FF | |
491fd90a JH |
612 | END |
613 | } | |
614 | ||
d5822f25 A |
615 | Imagine that the here-doc end marker is at the beginning of the line. |
616 | Now you can use C<\p{InKana}> and C<\P{InKana}>. | |
491fd90a JH |
617 | |
618 | You could also have used the existing block property names: | |
619 | ||
620 | sub InKana { | |
621 | return <<'END'; | |
622 | +utf8::InHiragana | |
623 | +utf8::InKatakana | |
624 | END | |
625 | } | |
626 | ||
627 | Suppose you wanted to match only the allocated characters, | |
d5822f25 | 628 | not the raw block ranges: in other words, you want to remove |
491fd90a JH |
629 | the non-characters: |
630 | ||
631 | sub InKana { | |
632 | return <<'END'; | |
633 | +utf8::InHiragana | |
634 | +utf8::InKatakana | |
635 | -utf8::IsCn | |
636 | END | |
637 | } | |
638 | ||
639 | The negation is useful for defining (surprise!) negated classes. | |
640 | ||
641 | sub InNotKana { | |
642 | return <<'END'; | |
643 | !utf8::InHiragana | |
644 | -utf8::InKatakana | |
645 | +utf8::IsCn | |
646 | END | |
647 | } | |
648 | ||
bac0b425 JP |
649 | Intersection is useful for getting the common characters matched by |
650 | two (or more) classes. | |
651 | ||
652 | sub InFooAndBar { | |
653 | return <<'END'; | |
654 | +main::Foo | |
655 | &main::Bar | |
656 | END | |
657 | } | |
658 | ||
659 | It's important to remember not to use "&" for the first set -- that | |
660 | would be intersecting with nothing (resulting in an empty set). | |
661 | ||
822502e5 TS |
662 | =head2 User-Defined Case Mappings |
663 | ||
3a2263fe RGS |
664 | You can also define your own mappings to be used in the lc(), |
665 | lcfirst(), uc(), and ucfirst() (or their string-inlined versions). | |
822502e5 | 666 | The principle is similar to that of user-defined character |
51f494cc | 667 | properties: to define subroutines |
3a2263fe RGS |
668 | with names like C<ToLower> (for lc() and lcfirst()), C<ToTitle> (for |
669 | the first character in ucfirst()), and C<ToUpper> (for uc(), and the | |
670 | rest of the characters in ucfirst()). | |
671 | ||
51f494cc KW |
672 | The string returned by the subroutines needs to be two hexadecimal numbers |
673 | separated by two tabulators: the source code point and the destination code | |
674 | point. For example: | |
3a2263fe RGS |
675 | |
676 | sub ToUpper { | |
677 | return <<END; | |
51f494cc | 678 | 0061\t\t0041 |
3a2263fe RGS |
679 | END |
680 | } | |
681 | ||
51f494cc KW |
682 | defines an uc() mapping that causes only the character "a" |
683 | to be mapped to "A"; all other characters will remain unchanged. | |
3a2263fe | 684 | |
51f494cc KW |
685 | (For serious hackers only) The above means you have to furnish a complete |
686 | mapping; you can't just override a couple of characters and leave the rest | |
687 | unchanged. You can find all the mappings in the directory | |
688 | C<$Config{privlib}>/F<unicore/To/>. The mapping data is returned as the | |
689 | here-document, and the C<utf8::ToSpecFoo> are special exception mappings | |
690 | derived from <$Config{privlib}>/F<unicore/SpecialCasing.txt>. The C<Digit> and | |
691 | C<Fold> mappings that one can see in the directory are not directly | |
692 | user-accessible, one can use either the C<Unicode::UCD> module, or just match | |
693 | case-insensitively (that's when the C<Fold> mapping is used). | |
3a2263fe | 694 | |
51f494cc KW |
695 | The mappings will only take effect on scalars that have been marked as having |
696 | Unicode characters, for example by using C<utf8::upgrade()>. | |
697 | Old byte-style strings are not affected. | |
3a2263fe | 698 | |
51f494cc | 699 | The mappings are in effect for the package they are defined in. |
3a2263fe | 700 | |
376d9008 | 701 | =head2 Character Encodings for Input and Output |
8cbd9a7a | 702 | |
7221edc9 | 703 | See L<Encode>. |
8cbd9a7a | 704 | |
c29a771d | 705 | =head2 Unicode Regular Expression Support Level |
776f8809 | 706 | |
376d9008 JB |
707 | The following list of Unicode support for regular expressions describes |
708 | all the features currently supported. The references to "Level N" | |
8158862b TS |
709 | and the section numbers refer to the Unicode Technical Standard #18, |
710 | "Unicode Regular Expressions", version 11, in May 2005. | |
776f8809 JH |
711 | |
712 | =over 4 | |
713 | ||
714 | =item * | |
715 | ||
716 | Level 1 - Basic Unicode Support | |
717 | ||
8158862b TS |
718 | RL1.1 Hex Notation - done [1] |
719 | RL1.2 Properties - done [2][3] | |
720 | RL1.2a Compatibility Properties - done [4] | |
721 | RL1.3 Subtraction and Intersection - MISSING [5] | |
722 | RL1.4 Simple Word Boundaries - done [6] | |
723 | RL1.5 Simple Loose Matches - done [7] | |
724 | RL1.6 Line Boundaries - MISSING [8] | |
725 | RL1.7 Supplementary Code Points - done [9] | |
726 | ||
727 | [1] \x{...} | |
728 | [2] \p{...} \P{...} | |
729 | [3] supports not only minimal list (general category, scripts, | |
730 | Alphabetic, Lowercase, Uppercase, WhiteSpace, | |
731 | NoncharacterCodePoint, DefaultIgnorableCodePoint, Any, | |
732 | ASCII, Assigned), but also bidirectional types, blocks, etc. | |
ea8b8ad2 | 733 | (see "Unicode Character Properties") |
8158862b TS |
734 | [4] \d \D \s \S \w \W \X [:prop:] [:^prop:] |
735 | [5] can use regular expression look-ahead [a] or | |
736 | user-defined character properties [b] to emulate set operations | |
737 | [6] \b \B | |
738 | [7] note that Perl does Full case-folding in matching, not Simple: | |
2bbc8d55 SP |
739 | for example U+1F88 is equivalent to U+1F00 U+03B9, |
740 | not with 1F80. This difference matters mainly for certain Greek | |
376d9008 JB |
741 | capital letters with certain modifiers: the Full case-folding |
742 | decomposes the letter, while the Simple case-folding would map | |
e0f9d4a8 | 743 | it to a single character. |
8158862b TS |
744 | [8] should do ^ and $ also on U+000B (\v in C), FF (\f), CR (\r), |
745 | CRLF (\r\n), NEL (U+0085), LS (U+2028), and PS (U+2029); | |
746 | should also affect <>, $., and script line numbers; | |
747 | should not split lines within CRLF [c] (i.e. there is no empty | |
748 | line between \r and \n) | |
749 | [9] UTF-8/UTF-EBDDIC used in perl allows not only U+10000 to U+10FFFF | |
750 | but also beyond U+10FFFF [d] | |
7207e29d | 751 | |
237bad5b | 752 | [a] You can mimic class subtraction using lookahead. |
8158862b | 753 | For example, what UTS#18 might write as |
29bdacb8 | 754 | |
dbe420b4 JH |
755 | [{Greek}-[{UNASSIGNED}]] |
756 | ||
757 | in Perl can be written as: | |
758 | ||
1d81abf3 JH |
759 | (?!\p{Unassigned})\p{InGreekAndCoptic} |
760 | (?=\p{Assigned})\p{InGreekAndCoptic} | |
dbe420b4 JH |
761 | |
762 | But in this particular example, you probably really want | |
763 | ||
1bfb14c4 | 764 | \p{GreekAndCoptic} |
dbe420b4 JH |
765 | |
766 | which will match assigned characters known to be part of the Greek script. | |
29bdacb8 | 767 | |
5ca1ac52 | 768 | Also see the Unicode::Regex::Set module, it does implement the full |
8158862b TS |
769 | UTS#18 grouping, intersection, union, and removal (subtraction) syntax. |
770 | ||
771 | [b] '+' for union, '-' for removal (set-difference), '&' for intersection | |
772 | (see L</"User-Defined Character Properties">) | |
773 | ||
774 | [c] Try the C<:crlf> layer (see L<PerlIO>). | |
5ca1ac52 | 775 | |
8158862b TS |
776 | [d] Avoid C<use warning 'utf8';> (or say C<no warning 'utf8';>) to allow |
777 | U+FFFF (C<\x{FFFF}>). | |
237bad5b | 778 | |
776f8809 JH |
779 | =item * |
780 | ||
781 | Level 2 - Extended Unicode Support | |
782 | ||
8158862b TS |
783 | RL2.1 Canonical Equivalents - MISSING [10][11] |
784 | RL2.2 Default Grapheme Clusters - MISSING [12][13] | |
785 | RL2.3 Default Word Boundaries - MISSING [14] | |
786 | RL2.4 Default Loose Matches - MISSING [15] | |
787 | RL2.5 Name Properties - MISSING [16] | |
788 | RL2.6 Wildcard Properties - MISSING | |
789 | ||
790 | [10] see UAX#15 "Unicode Normalization Forms" | |
791 | [11] have Unicode::Normalize but not integrated to regexes | |
792 | [12] have \X but at this level . should equal that | |
793 | [13] UAX#29 "Text Boundaries" considers CRLF and Hangul syllable | |
794 | clusters as a single grapheme cluster. | |
795 | [14] see UAX#29, Word Boundaries | |
796 | [15] see UAX#21 "Case Mappings" | |
797 | [16] have \N{...} but neither compute names of CJK Ideographs | |
798 | and Hangul Syllables nor use a loose match [e] | |
799 | ||
800 | [e] C<\N{...}> allows namespaces (see L<charnames>). | |
776f8809 JH |
801 | |
802 | =item * | |
803 | ||
8158862b TS |
804 | Level 3 - Tailored Support |
805 | ||
806 | RL3.1 Tailored Punctuation - MISSING | |
807 | RL3.2 Tailored Grapheme Clusters - MISSING [17][18] | |
808 | RL3.3 Tailored Word Boundaries - MISSING | |
809 | RL3.4 Tailored Loose Matches - MISSING | |
810 | RL3.5 Tailored Ranges - MISSING | |
811 | RL3.6 Context Matching - MISSING [19] | |
812 | RL3.7 Incremental Matches - MISSING | |
813 | ( RL3.8 Unicode Set Sharing ) | |
814 | RL3.9 Possible Match Sets - MISSING | |
815 | RL3.10 Folded Matching - MISSING [20] | |
816 | RL3.11 Submatchers - MISSING | |
817 | ||
818 | [17] see UAX#10 "Unicode Collation Algorithms" | |
819 | [18] have Unicode::Collate but not integrated to regexes | |
820 | [19] have (?<=x) and (?=x), but look-aheads or look-behinds should see | |
821 | outside of the target substring | |
822 | [20] need insensitive matching for linguistic features other than case; | |
823 | for example, hiragana to katakana, wide and narrow, simplified Han | |
824 | to traditional Han (see UTR#30 "Character Foldings") | |
776f8809 JH |
825 | |
826 | =back | |
827 | ||
c349b1b9 JH |
828 | =head2 Unicode Encodings |
829 | ||
376d9008 JB |
830 | Unicode characters are assigned to I<code points>, which are abstract |
831 | numbers. To use these numbers, various encodings are needed. | |
c349b1b9 JH |
832 | |
833 | =over 4 | |
834 | ||
c29a771d | 835 | =item * |
5cb3728c RB |
836 | |
837 | UTF-8 | |
c349b1b9 | 838 | |
3e4dbfed | 839 | UTF-8 is a variable-length (1 to 6 bytes, current character allocations |
376d9008 JB |
840 | require 4 bytes), byte-order independent encoding. For ASCII (and we |
841 | really do mean 7-bit ASCII, not another 8-bit encoding), UTF-8 is | |
842 | transparent. | |
c349b1b9 | 843 | |
8c007b5a | 844 | The following table is from Unicode 3.2. |
05632f9a JH |
845 | |
846 | Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte | |
847 | ||
8c007b5a JH |
848 | U+0000..U+007F 00..7F |
849 | U+0080..U+07FF C2..DF 80..BF | |
ec90690f TS |
850 | U+0800..U+0FFF E0 A0..BF 80..BF |
851 | U+1000..U+CFFF E1..EC 80..BF 80..BF | |
852 | U+D000..U+D7FF ED 80..9F 80..BF | |
8c007b5a | 853 | U+D800..U+DFFF ******* ill-formed ******* |
ec90690f | 854 | U+E000..U+FFFF EE..EF 80..BF 80..BF |
05632f9a JH |
855 | U+10000..U+3FFFF F0 90..BF 80..BF 80..BF |
856 | U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF | |
857 | U+100000..U+10FFFF F4 80..8F 80..BF 80..BF | |
858 | ||
376d9008 JB |
859 | Note the C<A0..BF> in C<U+0800..U+0FFF>, the C<80..9F> in |
860 | C<U+D000...U+D7FF>, the C<90..B>F in C<U+10000..U+3FFFF>, and the | |
861 | C<80...8F> in C<U+100000..U+10FFFF>. The "gaps" are caused by legal | |
862 | UTF-8 avoiding non-shortest encodings: it is technically possible to | |
863 | UTF-8-encode a single code point in different ways, but that is | |
864 | explicitly forbidden, and the shortest possible encoding should always | |
865 | be used. So that's what Perl does. | |
37361303 | 866 | |
376d9008 | 867 | Another way to look at it is via bits: |
05632f9a JH |
868 | |
869 | Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte | |
870 | ||
871 | 0aaaaaaa 0aaaaaaa | |
872 | 00000bbbbbaaaaaa 110bbbbb 10aaaaaa | |
873 | ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa | |
874 | 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa | |
875 | ||
876 | As you can see, the continuation bytes all begin with C<10>, and the | |
8c007b5a | 877 | leading bits of the start byte tell how many bytes the are in the |
05632f9a JH |
878 | encoded character. |
879 | ||
c29a771d | 880 | =item * |
5cb3728c RB |
881 | |
882 | UTF-EBCDIC | |
dbe420b4 | 883 | |
376d9008 | 884 | Like UTF-8 but EBCDIC-safe, in the way that UTF-8 is ASCII-safe. |
dbe420b4 | 885 | |
c29a771d | 886 | =item * |
5cb3728c | 887 | |
1e54db1a | 888 | UTF-16, UTF-16BE, UTF-16LE, Surrogates, and BOMs (Byte Order Marks) |
c349b1b9 | 889 | |
1bfb14c4 JH |
890 | The followings items are mostly for reference and general Unicode |
891 | knowledge, Perl doesn't use these constructs internally. | |
dbe420b4 | 892 | |
c349b1b9 | 893 | UTF-16 is a 2 or 4 byte encoding. The Unicode code points |
1bfb14c4 JH |
894 | C<U+0000..U+FFFF> are stored in a single 16-bit unit, and the code |
895 | points C<U+10000..U+10FFFF> in two 16-bit units. The latter case is | |
c349b1b9 JH |
896 | using I<surrogates>, the first 16-bit unit being the I<high |
897 | surrogate>, and the second being the I<low surrogate>. | |
898 | ||
376d9008 | 899 | Surrogates are code points set aside to encode the C<U+10000..U+10FFFF> |
c349b1b9 | 900 | range of Unicode code points in pairs of 16-bit units. The I<high |
376d9008 JB |
901 | surrogates> are the range C<U+D800..U+DBFF>, and the I<low surrogates> |
902 | are the range C<U+DC00..U+DFFF>. The surrogate encoding is | |
c349b1b9 JH |
903 | |
904 | $hi = ($uni - 0x10000) / 0x400 + 0xD800; | |
905 | $lo = ($uni - 0x10000) % 0x400 + 0xDC00; | |
906 | ||
907 | and the decoding is | |
908 | ||
1a3fa709 | 909 | $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00); |
c349b1b9 | 910 | |
feda178f | 911 | If you try to generate surrogates (for example by using chr()), you |
376d9008 JB |
912 | will get a warning if warnings are turned on, because those code |
913 | points are not valid for a Unicode character. | |
9466bab6 | 914 | |
376d9008 | 915 | Because of the 16-bitness, UTF-16 is byte-order dependent. UTF-16 |
c349b1b9 | 916 | itself can be used for in-memory computations, but if storage or |
376d9008 JB |
917 | transfer is required either UTF-16BE (big-endian) or UTF-16LE |
918 | (little-endian) encodings must be chosen. | |
c349b1b9 JH |
919 | |
920 | This introduces another problem: what if you just know that your data | |
376d9008 JB |
921 | is UTF-16, but you don't know which endianness? Byte Order Marks, or |
922 | BOMs, are a solution to this. A special character has been reserved | |
86bbd6d1 | 923 | in Unicode to function as a byte order marker: the character with the |
376d9008 | 924 | code point C<U+FEFF> is the BOM. |
042da322 | 925 | |
c349b1b9 | 926 | The trick is that if you read a BOM, you will know the byte order, |
376d9008 JB |
927 | since if it was written on a big-endian platform, you will read the |
928 | bytes C<0xFE 0xFF>, but if it was written on a little-endian platform, | |
929 | you will read the bytes C<0xFF 0xFE>. (And if the originating platform | |
930 | was writing in UTF-8, you will read the bytes C<0xEF 0xBB 0xBF>.) | |
042da322 | 931 | |
86bbd6d1 | 932 | The way this trick works is that the character with the code point |
376d9008 JB |
933 | C<U+FFFE> is guaranteed not to be a valid Unicode character, so the |
934 | sequence of bytes C<0xFF 0xFE> is unambiguously "BOM, represented in | |
1bfb14c4 | 935 | little-endian format" and cannot be C<U+FFFE>, represented in big-endian |
042da322 | 936 | format". |
c349b1b9 | 937 | |
c29a771d | 938 | =item * |
5cb3728c | 939 | |
1e54db1a | 940 | UTF-32, UTF-32BE, UTF-32LE |
c349b1b9 JH |
941 | |
942 | The UTF-32 family is pretty much like the UTF-16 family, expect that | |
042da322 | 943 | the units are 32-bit, and therefore the surrogate scheme is not |
376d9008 JB |
944 | needed. The BOM signatures will be C<0x00 0x00 0xFE 0xFF> for BE and |
945 | C<0xFF 0xFE 0x00 0x00> for LE. | |
c349b1b9 | 946 | |
c29a771d | 947 | =item * |
5cb3728c RB |
948 | |
949 | UCS-2, UCS-4 | |
c349b1b9 | 950 | |
86bbd6d1 | 951 | Encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit |
376d9008 | 952 | encoding. Unlike UTF-16, UCS-2 is not extensible beyond C<U+FFFF>, |
339cfa0e JH |
953 | because it does not use surrogates. UCS-4 is a 32-bit encoding, |
954 | functionally identical to UTF-32. | |
c349b1b9 | 955 | |
c29a771d | 956 | =item * |
5cb3728c RB |
957 | |
958 | UTF-7 | |
c349b1b9 | 959 | |
376d9008 JB |
960 | A seven-bit safe (non-eight-bit) encoding, which is useful if the |
961 | transport or storage is not eight-bit safe. Defined by RFC 2152. | |
c349b1b9 | 962 | |
95a1a48b JH |
963 | =back |
964 | ||
0d7c09bb JH |
965 | =head2 Security Implications of Unicode |
966 | ||
967 | =over 4 | |
968 | ||
969 | =item * | |
970 | ||
971 | Malformed UTF-8 | |
bf0fa0b2 JH |
972 | |
973 | Unfortunately, the specification of UTF-8 leaves some room for | |
974 | interpretation of how many bytes of encoded output one should generate | |
376d9008 JB |
975 | from one input Unicode character. Strictly speaking, the shortest |
976 | possible sequence of UTF-8 bytes should be generated, | |
977 | because otherwise there is potential for an input buffer overflow at | |
feda178f | 978 | the receiving end of a UTF-8 connection. Perl always generates the |
376d9008 JB |
979 | shortest length UTF-8, and with warnings on Perl will warn about |
980 | non-shortest length UTF-8 along with other malformations, such as the | |
981 | surrogates, which are not real Unicode code points. | |
bf0fa0b2 | 982 | |
0d7c09bb JH |
983 | =item * |
984 | ||
985 | Regular expressions behave slightly differently between byte data and | |
376d9008 JB |
986 | character (Unicode) data. For example, the "word character" character |
987 | class C<\w> will work differently depending on if data is eight-bit bytes | |
988 | or Unicode. | |
0d7c09bb | 989 | |
376d9008 JB |
990 | In the first case, the set of C<\w> characters is either small--the |
991 | default set of alphabetic characters, digits, and the "_"--or, if you | |
0d7c09bb JH |
992 | are using a locale (see L<perllocale>), the C<\w> might contain a few |
993 | more letters according to your language and country. | |
994 | ||
376d9008 | 995 | In the second case, the C<\w> set of characters is much, much larger. |
1bfb14c4 JH |
996 | Most importantly, even in the set of the first 256 characters, it will |
997 | probably match different characters: unlike most locales, which are | |
998 | specific to a language and country pair, Unicode classifies all the | |
999 | characters that are letters I<somewhere> as C<\w>. For example, your | |
1000 | locale might not think that LATIN SMALL LETTER ETH is a letter (unless | |
1001 | you happen to speak Icelandic), but Unicode does. | |
0d7c09bb | 1002 | |
376d9008 | 1003 | As discussed elsewhere, Perl has one foot (two hooves?) planted in |
1bfb14c4 JH |
1004 | each of two worlds: the old world of bytes and the new world of |
1005 | characters, upgrading from bytes to characters when necessary. | |
376d9008 JB |
1006 | If your legacy code does not explicitly use Unicode, no automatic |
1007 | switch-over to characters should happen. Characters shouldn't get | |
1bfb14c4 JH |
1008 | downgraded to bytes, either. It is possible to accidentally mix bytes |
1009 | and characters, however (see L<perluniintro>), in which case C<\w> in | |
1010 | regular expressions might start behaving differently. Review your | |
1011 | code. Use warnings and the C<strict> pragma. | |
0d7c09bb JH |
1012 | |
1013 | =back | |
1014 | ||
c349b1b9 JH |
1015 | =head2 Unicode in Perl on EBCDIC |
1016 | ||
376d9008 JB |
1017 | The way Unicode is handled on EBCDIC platforms is still |
1018 | experimental. On such platforms, references to UTF-8 encoding in this | |
1019 | document and elsewhere should be read as meaning the UTF-EBCDIC | |
1020 | specified in Unicode Technical Report 16, unless ASCII vs. EBCDIC issues | |
c349b1b9 | 1021 | are specifically discussed. There is no C<utfebcdic> pragma or |
376d9008 | 1022 | ":utfebcdic" layer; rather, "utf8" and ":utf8" are reused to mean |
86bbd6d1 PN |
1023 | the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic> |
1024 | for more discussion of the issues. | |
c349b1b9 | 1025 | |
b310b053 JH |
1026 | =head2 Locales |
1027 | ||
4616122b | 1028 | Usually locale settings and Unicode do not affect each other, but |
b310b053 JH |
1029 | there are a couple of exceptions: |
1030 | ||
1031 | =over 4 | |
1032 | ||
1033 | =item * | |
1034 | ||
8aa8f774 JH |
1035 | You can enable automatic UTF-8-ification of your standard file |
1036 | handles, default C<open()> layer, and C<@ARGV> by using either | |
1037 | the C<-C> command line switch or the C<PERL_UNICODE> environment | |
1038 | variable, see L<perlrun> for the documentation of the C<-C> switch. | |
b310b053 JH |
1039 | |
1040 | =item * | |
1041 | ||
376d9008 JB |
1042 | Perl tries really hard to work both with Unicode and the old |
1043 | byte-oriented world. Most often this is nice, but sometimes Perl's | |
1044 | straddling of the proverbial fence causes problems. | |
b310b053 JH |
1045 | |
1046 | =back | |
1047 | ||
1aad1664 JH |
1048 | =head2 When Unicode Does Not Happen |
1049 | ||
1050 | While Perl does have extensive ways to input and output in Unicode, | |
1051 | and few other 'entry points' like the @ARGV which can be interpreted | |
1052 | as Unicode (UTF-8), there still are many places where Unicode (in some | |
1053 | encoding or another) could be given as arguments or received as | |
1054 | results, or both, but it is not. | |
1055 | ||
6cd4dd6c JH |
1056 | The following are such interfaces. For all of these interfaces Perl |
1057 | currently (as of 5.8.3) simply assumes byte strings both as arguments | |
1058 | and results, or UTF-8 strings if the C<encoding> pragma has been used. | |
1aad1664 JH |
1059 | |
1060 | One reason why Perl does not attempt to resolve the role of Unicode in | |
1061 | this cases is that the answers are highly dependent on the operating | |
1062 | system and the file system(s). For example, whether filenames can be | |
1063 | in Unicode, and in exactly what kind of encoding, is not exactly a | |
1064 | portable concept. Similarly for the qx and system: how well will the | |
1065 | 'command line interface' (and which of them?) handle Unicode? | |
1066 | ||
1067 | =over 4 | |
1068 | ||
557a2462 RB |
1069 | =item * |
1070 | ||
51f494cc | 1071 | chdir, chmod, chown, chroot, exec, link, lstat, mkdir, |
1e8e8236 | 1072 | rename, rmdir, stat, symlink, truncate, unlink, utime, -X |
557a2462 RB |
1073 | |
1074 | =item * | |
1075 | ||
1076 | %ENV | |
1077 | ||
1078 | =item * | |
1079 | ||
1080 | glob (aka the <*>) | |
1081 | ||
1082 | =item * | |
1aad1664 | 1083 | |
557a2462 | 1084 | open, opendir, sysopen |
1aad1664 | 1085 | |
557a2462 | 1086 | =item * |
1aad1664 | 1087 | |
557a2462 | 1088 | qx (aka the backtick operator), system |
1aad1664 | 1089 | |
557a2462 | 1090 | =item * |
1aad1664 | 1091 | |
557a2462 | 1092 | readdir, readlink |
1aad1664 JH |
1093 | |
1094 | =back | |
1095 | ||
1096 | =head2 Forcing Unicode in Perl (Or Unforcing Unicode in Perl) | |
1097 | ||
1098 | Sometimes (see L</"When Unicode Does Not Happen">) there are | |
2bbc8d55 SP |
1099 | situations where you simply need to force a byte |
1100 | string into UTF-8, or vice versa. The low-level calls | |
1101 | utf8::upgrade($bytestring) and utf8::downgrade($utf8string[, FAIL_OK]) are | |
1aad1664 JH |
1102 | the answers. |
1103 | ||
2bbc8d55 SP |
1104 | Note that utf8::downgrade() can fail if the string contains characters |
1105 | that don't fit into a byte. | |
1aad1664 | 1106 | |
95a1a48b JH |
1107 | =head2 Using Unicode in XS |
1108 | ||
3a2263fe RGS |
1109 | If you want to handle Perl Unicode in XS extensions, you may find the |
1110 | following C APIs useful. See also L<perlguts/"Unicode Support"> for an | |
1111 | explanation about Unicode at the XS level, and L<perlapi> for the API | |
1112 | details. | |
95a1a48b JH |
1113 | |
1114 | =over 4 | |
1115 | ||
1116 | =item * | |
1117 | ||
1bfb14c4 | 1118 | C<DO_UTF8(sv)> returns true if the C<UTF8> flag is on and the bytes |
2bbc8d55 | 1119 | pragma is not in effect. C<SvUTF8(sv)> returns true if the C<UTF8> |
1bfb14c4 JH |
1120 | flag is on; the bytes pragma is ignored. The C<UTF8> flag being on |
1121 | does B<not> mean that there are any characters of code points greater | |
1122 | than 255 (or 127) in the scalar or that there are even any characters | |
1123 | in the scalar. What the C<UTF8> flag means is that the sequence of | |
1124 | octets in the representation of the scalar is the sequence of UTF-8 | |
1125 | encoded code points of the characters of a string. The C<UTF8> flag | |
1126 | being off means that each octet in this representation encodes a | |
1127 | single character with code point 0..255 within the string. Perl's | |
1128 | Unicode model is not to use UTF-8 until it is absolutely necessary. | |
95a1a48b JH |
1129 | |
1130 | =item * | |
1131 | ||
2bbc8d55 | 1132 | C<uvchr_to_utf8(buf, chr)> writes a Unicode character code point into |
1bfb14c4 | 1133 | a buffer encoding the code point as UTF-8, and returns a pointer |
2bbc8d55 | 1134 | pointing after the UTF-8 bytes. It works appropriately on EBCDIC machines. |
95a1a48b JH |
1135 | |
1136 | =item * | |
1137 | ||
2bbc8d55 | 1138 | C<utf8_to_uvchr(buf, lenp)> reads UTF-8 encoded bytes from a buffer and |
376d9008 | 1139 | returns the Unicode character code point and, optionally, the length of |
2bbc8d55 | 1140 | the UTF-8 byte sequence. It works appropriately on EBCDIC machines. |
95a1a48b JH |
1141 | |
1142 | =item * | |
1143 | ||
376d9008 JB |
1144 | C<utf8_length(start, end)> returns the length of the UTF-8 encoded buffer |
1145 | in characters. C<sv_len_utf8(sv)> returns the length of the UTF-8 encoded | |
95a1a48b JH |
1146 | scalar. |
1147 | ||
1148 | =item * | |
1149 | ||
376d9008 JB |
1150 | C<sv_utf8_upgrade(sv)> converts the string of the scalar to its UTF-8 |
1151 | encoded form. C<sv_utf8_downgrade(sv)> does the opposite, if | |
1152 | possible. C<sv_utf8_encode(sv)> is like sv_utf8_upgrade except that | |
1153 | it does not set the C<UTF8> flag. C<sv_utf8_decode()> does the | |
1154 | opposite of C<sv_utf8_encode()>. Note that none of these are to be | |
1155 | used as general-purpose encoding or decoding interfaces: C<use Encode> | |
1156 | for that. C<sv_utf8_upgrade()> is affected by the encoding pragma | |
1157 | but C<sv_utf8_downgrade()> is not (since the encoding pragma is | |
1158 | designed to be a one-way street). | |
95a1a48b JH |
1159 | |
1160 | =item * | |
1161 | ||
376d9008 | 1162 | C<is_utf8_char(s)> returns true if the pointer points to a valid UTF-8 |
90f968e0 | 1163 | character. |
95a1a48b JH |
1164 | |
1165 | =item * | |
1166 | ||
376d9008 | 1167 | C<is_utf8_string(buf, len)> returns true if C<len> bytes of the buffer |
95a1a48b JH |
1168 | are valid UTF-8. |
1169 | ||
1170 | =item * | |
1171 | ||
376d9008 JB |
1172 | C<UTF8SKIP(buf)> will return the number of bytes in the UTF-8 encoded |
1173 | character in the buffer. C<UNISKIP(chr)> will return the number of bytes | |
1174 | required to UTF-8-encode the Unicode character code point. C<UTF8SKIP()> | |
90f968e0 | 1175 | is useful for example for iterating over the characters of a UTF-8 |
376d9008 | 1176 | encoded buffer; C<UNISKIP()> is useful, for example, in computing |
90f968e0 | 1177 | the size required for a UTF-8 encoded buffer. |
95a1a48b JH |
1178 | |
1179 | =item * | |
1180 | ||
376d9008 | 1181 | C<utf8_distance(a, b)> will tell the distance in characters between the |
95a1a48b JH |
1182 | two pointers pointing to the same UTF-8 encoded buffer. |
1183 | ||
1184 | =item * | |
1185 | ||
2bbc8d55 | 1186 | C<utf8_hop(s, off)> will return a pointer to a UTF-8 encoded buffer |
376d9008 JB |
1187 | that is C<off> (positive or negative) Unicode characters displaced |
1188 | from the UTF-8 buffer C<s>. Be careful not to overstep the buffer: | |
1189 | C<utf8_hop()> will merrily run off the end or the beginning of the | |
1190 | buffer if told to do so. | |
95a1a48b | 1191 | |
d2cc3551 JH |
1192 | =item * |
1193 | ||
376d9008 JB |
1194 | C<pv_uni_display(dsv, spv, len, pvlim, flags)> and |
1195 | C<sv_uni_display(dsv, ssv, pvlim, flags)> are useful for debugging the | |
1196 | output of Unicode strings and scalars. By default they are useful | |
1197 | only for debugging--they display B<all> characters as hexadecimal code | |
1bfb14c4 JH |
1198 | points--but with the flags C<UNI_DISPLAY_ISPRINT>, |
1199 | C<UNI_DISPLAY_BACKSLASH>, and C<UNI_DISPLAY_QQ> you can make the | |
1200 | output more readable. | |
d2cc3551 JH |
1201 | |
1202 | =item * | |
1203 | ||
2bbc8d55 | 1204 | C<ibcmp_utf8(s1, pe1, l1, u1, s2, pe2, l2, u2)> can be used to |
376d9008 JB |
1205 | compare two strings case-insensitively in Unicode. For case-sensitive |
1206 | comparisons you can just use C<memEQ()> and C<memNE()> as usual. | |
d2cc3551 | 1207 | |
c349b1b9 JH |
1208 | =back |
1209 | ||
95a1a48b JH |
1210 | For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h> |
1211 | in the Perl source code distribution. | |
1212 | ||
c29a771d JH |
1213 | =head1 BUGS |
1214 | ||
376d9008 | 1215 | =head2 Interaction with Locales |
7eabb34d | 1216 | |
376d9008 JB |
1217 | Use of locales with Unicode data may lead to odd results. Currently, |
1218 | Perl attempts to attach 8-bit locale info to characters in the range | |
1219 | 0..255, but this technique is demonstrably incorrect for locales that | |
1220 | use characters above that range when mapped into Unicode. Perl's | |
1221 | Unicode support will also tend to run slower. Use of locales with | |
1222 | Unicode is discouraged. | |
c29a771d | 1223 | |
2bbc8d55 SP |
1224 | =head2 Problems with characters whose ordinal numbers are in the range 128 - 255 with no Locale specified |
1225 | ||
1226 | Without a locale specified, unlike all other characters or code points, | |
1227 | these characters have very different semantics in byte semantics versus | |
1228 | character semantics. | |
1229 | In character semantics they are interpreted as Unicode code points, which means | |
1230 | they are viewed as Latin-1 (ISO-8859-1). | |
1231 | In byte semantics, they are considered to be unassigned characters, | |
1232 | meaning that the only semantics they have is their | |
1233 | ordinal numbers, and that they are not members of various character classes. | |
1234 | None are considered to match C<\w> for example, but all match C<\W>. | |
1235 | Besides these class matches, | |
1236 | the known operations that this affects are those that change the case, | |
1237 | regular expression matching while ignoring case, | |
1238 | and B<quotemeta()>. | |
1239 | This can lead to unexpected results in which a string's semantics suddenly | |
1240 | change if a code point above 255 is appended to or removed from it, | |
1241 | which changes the string's semantics from byte to character or vice versa. | |
1242 | This behavior is scheduled to change in version 5.12, but in the meantime, | |
fe749c9a KW |
1243 | a workaround is to always call utf8::upgrade($string), or to use the |
1244 | standard modules L<Encode> or L<charnames>. | |
2bbc8d55 | 1245 | |
376d9008 | 1246 | =head2 Interaction with Extensions |
7eabb34d | 1247 | |
376d9008 | 1248 | When Perl exchanges data with an extension, the extension should be |
2575c402 | 1249 | able to understand the UTF8 flag and act accordingly. If the |
376d9008 JB |
1250 | extension doesn't know about the flag, it's likely that the extension |
1251 | will return incorrectly-flagged data. | |
7eabb34d A |
1252 | |
1253 | So if you're working with Unicode data, consult the documentation of | |
1254 | every module you're using if there are any issues with Unicode data | |
1255 | exchange. If the documentation does not talk about Unicode at all, | |
a73d23f6 | 1256 | suspect the worst and probably look at the source to learn how the |
376d9008 | 1257 | module is implemented. Modules written completely in Perl shouldn't |
a73d23f6 RGS |
1258 | cause problems. Modules that directly or indirectly access code written |
1259 | in other programming languages are at risk. | |
7eabb34d | 1260 | |
376d9008 | 1261 | For affected functions, the simple strategy to avoid data corruption is |
7eabb34d | 1262 | to always make the encoding of the exchanged data explicit. Choose an |
376d9008 | 1263 | encoding that you know the extension can handle. Convert arguments passed |
7eabb34d A |
1264 | to the extensions to that encoding and convert results back from that |
1265 | encoding. Write wrapper functions that do the conversions for you, so | |
1266 | you can later change the functions when the extension catches up. | |
1267 | ||
376d9008 | 1268 | To provide an example, let's say the popular Foo::Bar::escape_html |
7eabb34d A |
1269 | function doesn't deal with Unicode data yet. The wrapper function |
1270 | would convert the argument to raw UTF-8 and convert the result back to | |
376d9008 | 1271 | Perl's internal representation like so: |
7eabb34d A |
1272 | |
1273 | sub my_escape_html ($) { | |
1274 | my($what) = shift; | |
1275 | return unless defined $what; | |
1276 | Encode::decode_utf8(Foo::Bar::escape_html(Encode::encode_utf8($what))); | |
1277 | } | |
1278 | ||
1279 | Sometimes, when the extension does not convert data but just stores | |
1280 | and retrieves them, you will be in a position to use the otherwise | |
1281 | dangerous Encode::_utf8_on() function. Let's say the popular | |
66b79f27 | 1282 | C<Foo::Bar> extension, written in C, provides a C<param> method that |
7eabb34d A |
1283 | lets you store and retrieve data according to these prototypes: |
1284 | ||
1285 | $self->param($name, $value); # set a scalar | |
1286 | $value = $self->param($name); # retrieve a scalar | |
1287 | ||
1288 | If it does not yet provide support for any encoding, one could write a | |
1289 | derived class with such a C<param> method: | |
1290 | ||
1291 | sub param { | |
1292 | my($self,$name,$value) = @_; | |
1293 | utf8::upgrade($name); # make sure it is UTF-8 encoded | |
af55fc6a | 1294 | if (defined $value) { |
7eabb34d A |
1295 | utf8::upgrade($value); # make sure it is UTF-8 encoded |
1296 | return $self->SUPER::param($name,$value); | |
1297 | } else { | |
1298 | my $ret = $self->SUPER::param($name); | |
1299 | Encode::_utf8_on($ret); # we know, it is UTF-8 encoded | |
1300 | return $ret; | |
1301 | } | |
1302 | } | |
1303 | ||
a73d23f6 RGS |
1304 | Some extensions provide filters on data entry/exit points, such as |
1305 | DB_File::filter_store_key and family. Look out for such filters in | |
66b79f27 | 1306 | the documentation of your extensions, they can make the transition to |
7eabb34d A |
1307 | Unicode data much easier. |
1308 | ||
376d9008 | 1309 | =head2 Speed |
7eabb34d | 1310 | |
c29a771d | 1311 | Some functions are slower when working on UTF-8 encoded strings than |
574c8022 | 1312 | on byte encoded strings. All functions that need to hop over |
7c17141f JH |
1313 | characters such as length(), substr() or index(), or matching regular |
1314 | expressions can work B<much> faster when the underlying data are | |
1315 | byte-encoded. | |
1316 | ||
1317 | In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1 | |
1318 | a caching scheme was introduced which will hopefully make the slowness | |
a104b433 JH |
1319 | somewhat less spectacular, at least for some operations. In general, |
1320 | operations with UTF-8 encoded strings are still slower. As an example, | |
1321 | the Unicode properties (character classes) like C<\p{Nd}> are known to | |
1322 | be quite a bit slower (5-20 times) than their simpler counterparts | |
1323 | like C<\d> (then again, there 268 Unicode characters matching C<Nd> | |
1324 | compared with the 10 ASCII characters matching C<d>). | |
666f95b9 | 1325 | |
fe749c9a KW |
1326 | =head2 Possible problems on EBCDIC platforms |
1327 | ||
1328 | In earlier versions, when byte and character data were concatenated, | |
1329 | the new string was sometimes created by | |
1330 | decoding the byte strings as I<ISO 8859-1 (Latin-1)>, even if the | |
1331 | old Unicode string used EBCDIC. | |
1332 | ||
1333 | If you find any of these, please report them as bugs. | |
1334 | ||
c8d992ba A |
1335 | =head2 Porting code from perl-5.6.X |
1336 | ||
1337 | Perl 5.8 has a different Unicode model from 5.6. In 5.6 the programmer | |
1338 | was required to use the C<utf8> pragma to declare that a given scope | |
1339 | expected to deal with Unicode data and had to make sure that only | |
1340 | Unicode data were reaching that scope. If you have code that is | |
1341 | working with 5.6, you will need some of the following adjustments to | |
1342 | your code. The examples are written such that the code will continue | |
1343 | to work under 5.6, so you should be safe to try them out. | |
1344 | ||
1345 | =over 4 | |
1346 | ||
1347 | =item * | |
1348 | ||
1349 | A filehandle that should read or write UTF-8 | |
1350 | ||
1351 | if ($] > 5.007) { | |
740d4bb2 | 1352 | binmode $fh, ":encoding(utf8)"; |
c8d992ba A |
1353 | } |
1354 | ||
1355 | =item * | |
1356 | ||
1357 | A scalar that is going to be passed to some extension | |
1358 | ||
1359 | Be it Compress::Zlib, Apache::Request or any extension that has no | |
1360 | mention of Unicode in the manpage, you need to make sure that the | |
2575c402 | 1361 | UTF8 flag is stripped off. Note that at the time of this writing |
c8d992ba A |
1362 | (October 2002) the mentioned modules are not UTF-8-aware. Please |
1363 | check the documentation to verify if this is still true. | |
1364 | ||
1365 | if ($] > 5.007) { | |
1366 | require Encode; | |
1367 | $val = Encode::encode_utf8($val); # make octets | |
1368 | } | |
1369 | ||
1370 | =item * | |
1371 | ||
1372 | A scalar we got back from an extension | |
1373 | ||
1374 | If you believe the scalar comes back as UTF-8, you will most likely | |
2575c402 | 1375 | want the UTF8 flag restored: |
c8d992ba A |
1376 | |
1377 | if ($] > 5.007) { | |
1378 | require Encode; | |
1379 | $val = Encode::decode_utf8($val); | |
1380 | } | |
1381 | ||
1382 | =item * | |
1383 | ||
1384 | Same thing, if you are really sure it is UTF-8 | |
1385 | ||
1386 | if ($] > 5.007) { | |
1387 | require Encode; | |
1388 | Encode::_utf8_on($val); | |
1389 | } | |
1390 | ||
1391 | =item * | |
1392 | ||
1393 | A wrapper for fetchrow_array and fetchrow_hashref | |
1394 | ||
1395 | When the database contains only UTF-8, a wrapper function or method is | |
1396 | a convenient way to replace all your fetchrow_array and | |
1397 | fetchrow_hashref calls. A wrapper function will also make it easier to | |
1398 | adapt to future enhancements in your database driver. Note that at the | |
1399 | time of this writing (October 2002), the DBI has no standardized way | |
1400 | to deal with UTF-8 data. Please check the documentation to verify if | |
1401 | that is still true. | |
1402 | ||
1403 | sub fetchrow { | |
1404 | my($self, $sth, $what) = @_; # $what is one of fetchrow_{array,hashref} | |
1405 | if ($] < 5.007) { | |
1406 | return $sth->$what; | |
1407 | } else { | |
1408 | require Encode; | |
1409 | if (wantarray) { | |
1410 | my @arr = $sth->$what; | |
1411 | for (@arr) { | |
1412 | defined && /[^\000-\177]/ && Encode::_utf8_on($_); | |
1413 | } | |
1414 | return @arr; | |
1415 | } else { | |
1416 | my $ret = $sth->$what; | |
1417 | if (ref $ret) { | |
1418 | for my $k (keys %$ret) { | |
1419 | defined && /[^\000-\177]/ && Encode::_utf8_on($_) for $ret->{$k}; | |
1420 | } | |
1421 | return $ret; | |
1422 | } else { | |
1423 | defined && /[^\000-\177]/ && Encode::_utf8_on($_) for $ret; | |
1424 | return $ret; | |
1425 | } | |
1426 | } | |
1427 | } | |
1428 | } | |
1429 | ||
1430 | ||
1431 | =item * | |
1432 | ||
1433 | A large scalar that you know can only contain ASCII | |
1434 | ||
1435 | Scalars that contain only ASCII and are marked as UTF-8 are sometimes | |
1436 | a drag to your program. If you recognize such a situation, just remove | |
2575c402 | 1437 | the UTF8 flag: |
c8d992ba A |
1438 | |
1439 | utf8::downgrade($val) if $] > 5.007; | |
1440 | ||
1441 | =back | |
1442 | ||
51f494cc KW |
1443 | =head2 Hacking Perl to work on earlier Unicode versions (for very serious hackers only) |
1444 | ||
1445 | Perl by default comes with the latest supported Unicode version built in, but | |
1446 | you can change to use any earlier one. | |
1447 | ||
1448 | Download the files in the version of Unicode that you want from the Unicode web | |
1449 | site L<http://www.unicode.org>). These should replace the existing files in | |
1450 | C<\$Config{privlib}>/F<unicore>. (C<\%Config> is available from the Config | |
1451 | module.) Follow the instructions in F<README.perl> in that directory to change | |
1452 | some of their names, and then run F<make>. | |
1453 | ||
1454 | It is even possible to download them to a different directory, and then change | |
1455 | F<utf8_heavy.pl> in the directory C<\$Config{privlib}> to point to the new | |
1456 | directory, or maybe make a copy of that directory before making the change, and | |
1457 | using C<@INC> or the C<-I> run-time flag to switch between versions at will, | |
1458 | but all this is beyond the scope of these instructions. | |
1459 | ||
393fec97 GS |
1460 | =head1 SEE ALSO |
1461 | ||
51f494cc | 1462 | L<perlunitut>, L<perluniintro>, L<perluniprops>, L<Encode>, L<open>, L<utf8>, L<bytes>, |
a05d7ebb | 1463 | L<perlretut>, L<perlvar/"${^UNICODE}"> |
51f494cc | 1464 | L<http://www.unicode.org/reports/tr44>). |
393fec97 GS |
1465 | |
1466 | =cut |