1PERLUNICODE(1) Perl Programmers Reference Guide PERLUNICODE(1)
2
3
4
6 perlunicode - Unicode support in Perl
7
9 If you haven't already, before reading this document, you should become
10 familiar with both perlunitut and perluniintro.
11
12 Unicode aims to UNI-fy the en-CODE-ings of all the world's character
13 sets into a single Standard. For quite a few of the various coding
14 standards that existed when Unicode was first created, converting from
15 each to Unicode essentially meant adding a constant to each code point
16 in the original standard, and converting back meant just subtracting
17 that same constant. For ASCII and ISO-8859-1, the constant is 0. For
18 ISO-8859-5, (Cyrillic) the constant is 864; for Hebrew (ISO-8859-8),
19 it's 1488; Thai (ISO-8859-11), 3424; and so forth. This made it easy
20 to do the conversions, and facilitated the adoption of Unicode.
21
22 And it worked; nowadays, those legacy standards are rarely used. Most
23 everyone uses Unicode.
24
25 Unicode is a comprehensive standard. It specifies many things outside
26 the scope of Perl, such as how to display sequences of characters. For
27 a full discussion of all aspects of Unicode, see
28 <http://www.unicode.org>.
29
30 Important Caveats
31 Even though some of this section may not be understandable to you on
32 first reading, we think it's important enough to highlight some of the
33 gotchas before delving further, so here goes:
34
35 Unicode support is an extensive requirement. While Perl does not
36 implement the Unicode standard or the accompanying technical reports
37 from cover to cover, Perl does support many Unicode features.
38
39 Also, the use of Unicode may present security issues that aren't
40 obvious, see "Security Implications of Unicode".
41
42 Safest if you "use feature 'unicode_strings'"
43 In order to preserve backward compatibility, Perl does not turn on
44 full internal Unicode support unless the pragma
45 "use feature 'unicode_strings'" is specified. (This is
46 automatically selected if you "use 5.012" or higher.) Failure to
47 do this can trigger unexpected surprises. See "The "Unicode Bug""
48 below.
49
50 This pragma doesn't affect I/O. Nor does it change the internal
51 representation of strings, only their interpretation. There are
52 still several places where Unicode isn't fully supported, such as
53 in filenames.
54
55 Input and Output Layers
56 Use the ":encoding(...)" layer to read from and write to
57 filehandles using the specified encoding. (See open.)
58
59 You should convert your non-ASCII, non-UTF-8 Perl scripts to be UTF-8.
60 See encoding.
61
62 "use utf8" still needed to enable UTF-8 in scripts
63 If your Perl script is itself encoded in UTF-8, the "use utf8"
64 pragma must be explicitly included to enable recognition of that
65 (in string or regular expression literals, or in identifier names).
66 This is the only time when an explicit "use utf8" is needed. (See
67 utf8).
68
69 If a Perl script begins with the bytes that form the UTF-8 encoding
70 of the Unicode BYTE ORDER MARK ("BOM", see "Unicode Encodings"),
71 those bytes are completely ignored.
72
73 UTF-16 scripts autodetected
74 If a Perl script begins with the Unicode "BOM" (UTF-16LE,
75 UTF16-BE), or if the script looks like non-"BOM"-marked UTF-16 of
76 either endianness, Perl will correctly read in the script as the
77 appropriate Unicode encoding.
78
79 Byte and Character Semantics
80 Before Unicode, most encodings used 8 bits (a single byte) to encode
81 each character. Thus a character was a byte, and a byte was a
82 character, and there could be only 256 or fewer possible characters.
83 "Byte Semantics" in the title of this section refers to this behavior.
84 There was no need to distinguish between "Byte" and "Character".
85
86 Then along comes Unicode which has room for over a million characters
87 (and Perl allows for even more). This means that a character may
88 require more than a single byte to represent it, and so the two terms
89 are no longer equivalent. What matter are the characters as whole
90 entities, and not usually the bytes that comprise them. That's what
91 the term "Character Semantics" in the title of this section refers to.
92
93 Perl had to change internally to decouple "bytes" from "characters".
94 It is important that you too change your ideas, if you haven't already,
95 so that "byte" and "character" no longer mean the same thing in your
96 mind.
97
98 The basic building block of Perl strings has always been a "character".
99 The changes basically come down to that the implementation no longer
100 thinks that a character is always just a single byte.
101
102 There are various things to note:
103
104 · String handling functions, for the most part, continue to operate
105 in terms of characters. "length()", for example, returns the
106 number of characters in a string, just as before. But that number
107 no longer is necessarily the same as the number of bytes in the
108 string (there may be more bytes than characters). The other such
109 functions include "chop()", "chomp()", "substr()", "pos()",
110 "index()", "rindex()", "sort()", "sprintf()", and "write()".
111
112 The exceptions are:
113
114 · the bit-oriented "vec"
115
116
117
118 · the byte-oriented "pack"/"unpack" "C" format
119
120 However, the "W" specifier does operate on whole characters, as
121 does the "U" specifier.
122
123 · some operators that interact with the platform's operating
124 system
125
126 Operators dealing with filenames are examples.
127
128 · when the functions are called from within the scope of the
129 "use bytes" pragma
130
131 Likely, you should use this only for debugging anyway.
132
133 · Strings--including hash keys--and regular expression patterns may
134 contain characters that have ordinal values larger than 255.
135
136 If you use a Unicode editor to edit your program, Unicode
137 characters may occur directly within the literal strings in UTF-8
138 encoding, or UTF-16. (The former requires a "use utf8", the latter
139 may require a "BOM".)
140
141 "Creating Unicode" in perluniintro gives other ways to place non-
142 ASCII characters in your strings.
143
144 · The "chr()" and "ord()" functions work on whole characters.
145
146 · Regular expressions match whole characters. For example, "."
147 matches a whole character instead of only a single byte.
148
149 · The "tr///" operator translates whole characters. (Note that the
150 "tr///CU" functionality has been removed. For similar
151 functionality to that, see "pack('U0', ...)" and "pack('C0',
152 ...)").
153
154 · "scalar reverse()" reverses by character rather than by byte.
155
156 · The bit string operators, "& | ^ ~" and (starting in v5.22) "&. |.
157 ^. ~." can operate on characters that don't fit into a byte.
158 However, the current behavior is likely to change. You should not
159 use these operators on strings that are encoded in UTF-8. If
160 you're not sure about the encoding of a string, downgrade it before
161 using any of these operators; you can use "utf8::utf8_downgrade()".
162
163 The bottom line is that Perl has always practiced "Character
164 Semantics", but with the advent of Unicode, that is now different than
165 "Byte Semantics".
166
167 ASCII Rules versus Unicode Rules
168 Before Unicode, when a character was a byte was a character, Perl knew
169 only about the 128 characters defined by ASCII, code points 0 through
170 127 (except for under "use locale"). That left the code points 128 to
171 255 as unassigned, and available for whatever use a program might want.
172 The only semantics they have is their ordinal numbers, and that they
173 are members of none of the non-negative character classes. None are
174 considered to match "\w" for example, but all match "\W".
175
176 Unicode, of course, assigns each of those code points a particular
177 meaning (along with ones above 255). To preserve backward
178 compatibility, Perl only uses the Unicode meanings when there is some
179 indication that Unicode is what is intended; otherwise the non-ASCII
180 code points remain treated as if they are unassigned.
181
182 Here are the ways that Perl knows that a string should be treated as
183 Unicode:
184
185 · Within the scope of "use utf8"
186
187 If the whole program is Unicode (signified by using 8-bit Unicode
188 Transformation Format), then all strings within it must be Unicode.
189
190 · Within the scope of "use feature 'unicode_strings'"
191
192 This pragma was created so you can explicitly tell Perl that
193 operations executed within its scope are to use Unicode rules.
194 More operations are affected with newer perls. See "The "Unicode
195 Bug"".
196
197 · Within the scope of "use 5.012" or higher
198
199 This implicitly turns on "use feature 'unicode_strings'".
200
201 · Within the scope of "use locale 'not_characters'", or "use locale"
202 and the current locale is a UTF-8 locale.
203
204 The former is defined to imply Unicode handling; and the latter
205 indicates a Unicode locale, hence a Unicode interpretation of all
206 strings within it.
207
208 · When the string contains a Unicode-only code point
209
210 Perl has never accepted code points above 255 without them being
211 Unicode, so their use implies Unicode for the whole string.
212
213 · When the string contains a Unicode named code point "\N{...}"
214
215 The "\N{...}" construct explicitly refers to a Unicode code point,
216 even if it is one that is also in ASCII. Therefore the string
217 containing it must be Unicode.
218
219 · When the string has come from an external source marked as Unicode
220
221 The "-C" command line option can specify that certain inputs to the
222 program are Unicode, and the values of this can be read by your
223 Perl code, see "${^UNICODE}" in perlvar.
224
225 · When the string has been upgraded to UTF-8
226
227 The function "utf8::utf8_upgrade()" can be explicitly used to
228 permanently (unless a subsequent "utf8::utf8_downgrade()" is
229 called) cause a string to be treated as Unicode.
230
231 · There are additional methods for regular expression patterns
232
233 A pattern that is compiled with the "/u" or "/a" modifiers is
234 treated as Unicode (though there are some restrictions with "/a").
235 Under the "/d" and "/l" modifiers, there are several other
236 indications for Unicode; see "Character set modifiers" in perlre.
237
238 Note that all of the above are overridden within the scope of "use
239 bytes"; but you should be using this pragma only for debugging.
240
241 Note also that some interactions with the platform's operating system
242 never use Unicode rules.
243
244 When Unicode rules are in effect:
245
246 · Case translation operators use the Unicode case translation tables.
247
248 Note that "uc()", or "\U" in interpolated strings, translates to
249 uppercase, while "ucfirst", or "\u" in interpolated strings,
250 translates to titlecase in languages that make the distinction
251 (which is equivalent to uppercase in languages without the
252 distinction).
253
254 There is a CPAN module, "Unicode::Casing", which allows you to
255 define your own mappings to be used in "lc()", "lcfirst()", "uc()",
256 "ucfirst()", and "fc" (or their double-quoted string inlined
257 versions such as "\U"). (Prior to Perl 5.16, this functionality
258 was partially provided in the Perl core, but suffered from a number
259 of insurmountable drawbacks, so the CPAN module was written
260 instead.)
261
262 · Character classes in regular expressions match based on the
263 character properties specified in the Unicode properties database.
264
265 "\w" can be used to match a Japanese ideograph, for instance; and
266 "[[:digit:]]" a Bengali number.
267
268 · Named Unicode properties, scripts, and block ranges may be used
269 (like bracketed character classes) by using the "\p{}" "matches
270 property" construct and the "\P{}" negation, "doesn't match
271 property".
272
273 See "Unicode Character Properties" for more details.
274
275 You can define your own character properties and use them in the
276 regular expression with the "\p{}" or "\P{}" construct. See "User-
277 Defined Character Properties" for more details.
278
279 Extended Grapheme Clusters (Logical characters)
280 Consider a character, say "H". It could appear with various marks
281 around it, such as an acute accent, or a circumflex, or various hooks,
282 circles, arrows, etc., above, below, to one side or the other, etc.
283 There are many possibilities among the world's languages. The number
284 of combinations is astronomical, and if there were a character for each
285 combination, it would soon exhaust Unicode's more than a million
286 possible characters. So Unicode took a different approach: there is a
287 character for the base "H", and a character for each of the possible
288 marks, and these can be variously combined to get a final logical
289 character. So a logical character--what appears to be a single
290 character--can be a sequence of more than one individual characters.
291 The Unicode standard calls these "extended grapheme clusters" (which is
292 an improved version of the no-longer much used "grapheme cluster");
293 Perl furnishes the "\X" regular expression construct to match such
294 sequences in their entirety.
295
296 But Unicode's intent is to unify the existing character set standards
297 and practices, and several pre-existing standards have single
298 characters that mean the same thing as some of these combinations, like
299 ISO-8859-1, which has quite a few of them. For example, "LATIN CAPITAL
300 LETTER E WITH ACUTE" was already in this standard when Unicode came
301 along. Unicode therefore added it to its repertoire as that single
302 character. But this character is considered by Unicode to be
303 equivalent to the sequence consisting of the character "LATIN CAPITAL
304 LETTER E" followed by the character "COMBINING ACUTE ACCENT".
305
306 "LATIN CAPITAL LETTER E WITH ACUTE" is called a "pre-composed"
307 character, and its equivalence with the "E" and the "COMBINING ACCENT"
308 sequence is called canonical equivalence. All pre-composed characters
309 are said to have a decomposition (into the equivalent sequence), and
310 the decomposition type is also called canonical. A string may be
311 comprised as much as possible of precomposed characters, or it may be
312 comprised of entirely decomposed characters. Unicode calls these
313 respectively, "Normalization Form Composed" (NFC) and "Normalization
314 Form Decomposed". The "Unicode::Normalize" module contains functions
315 that convert between the two. A string may also have both composed
316 characters and decomposed characters; this module can be used to make
317 it all one or the other.
318
319 You may be presented with strings in any of these equivalent forms.
320 There is currently nothing in Perl 5 that ignores the differences. So
321 you'll have to specially hanlde it. The usual advice is to convert
322 your inputs to "NFD" before processing further.
323
324 For more detailed information, see <http://unicode.org/reports/tr15/>.
325
326 Unicode Character Properties
327 (The only time that Perl considers a sequence of individual code points
328 as a single logical character is in the "\X" construct, already
329 mentioned above. Therefore "character" in this discussion means a
330 single Unicode code point.)
331
332 Very nearly all Unicode character properties are accessible through
333 regular expressions by using the "\p{}" "matches property" construct
334 and the "\P{}" "doesn't match property" for its negation.
335
336 For instance, "\p{Uppercase}" matches any single character with the
337 Unicode "Uppercase" property, while "\p{L}" matches any character with
338 a "General_Category" of "L" (letter) property (see "General_Category"
339 below). Brackets are not required for single letter property names, so
340 "\p{L}" is equivalent to "\pL".
341
342 More formally, "\p{Uppercase}" matches any single character whose
343 Unicode "Uppercase" property value is "True", and "\P{Uppercase}"
344 matches any character whose "Uppercase" property value is "False", and
345 they could have been written as "\p{Uppercase=True}" and
346 "\p{Uppercase=False}", respectively.
347
348 This formality is needed when properties are not binary; that is, if
349 they can take on more values than just "True" and "False". For
350 example, the "Bidi_Class" property (see "Bidirectional Character Types"
351 below), can take on several different values, such as "Left", "Right",
352 "Whitespace", and others. To match these, one needs to specify both
353 the property name ("Bidi_Class"), AND the value being matched against
354 ("Left", "Right", etc.). This is done, as in the examples above, by
355 having the two components separated by an equal sign (or
356 interchangeably, a colon), like "\p{Bidi_Class: Left}".
357
358 All Unicode-defined character properties may be written in these
359 compound forms of "\p{property=value}" or "\p{property:value}", but
360 Perl provides some additional properties that are written only in the
361 single form, as well as single-form short-cuts for all binary
362 properties and certain others described below, in which you may omit
363 the property name and the equals or colon separator.
364
365 Most Unicode character properties have at least two synonyms (or
366 aliases if you prefer): a short one that is easier to type and a longer
367 one that is more descriptive and hence easier to understand. Thus the
368 "L" and "Letter" properties above are equivalent and can be used
369 interchangeably. Likewise, "Upper" is a synonym for "Uppercase", and
370 we could have written "\p{Uppercase}" equivalently as "\p{Upper}".
371 Also, there are typically various synonyms for the values the property
372 can be. For binary properties, "True" has 3 synonyms: "T", "Yes", and
373 "Y"; and "False" has correspondingly "F", "No", and "N". But be
374 careful. A short form of a value for one property may not mean the
375 same thing as the same short form for another. Thus, for the
376 "General_Category" property, "L" means "Letter", but for the
377 "Bidi_Class" property, "L" means "Left". A complete list of properties
378 and synonyms is in perluniprops.
379
380 Upper/lower case differences in property names and values are
381 irrelevant; thus "\p{Upper}" means the same thing as "\p{upper}" or
382 even "\p{UpPeR}". Similarly, you can add or subtract underscores
383 anywhere in the middle of a word, so that these are also equivalent to
384 "\p{U_p_p_e_r}". And white space is irrelevant adjacent to non-word
385 characters, such as the braces and the equals or colon separators, so
386 "\p{ Upper }" and "\p{ Upper_case : Y }" are equivalent to these as
387 well. In fact, white space and even hyphens can usually be added or
388 deleted anywhere. So even "\p{ Up-per case = Yes}" is equivalent. All
389 this is called "loose-matching" by Unicode. The few places where
390 stricter matching is used is in the middle of numbers, and in the Perl
391 extension properties that begin or end with an underscore. Stricter
392 matching cares about white space (except adjacent to non-word
393 characters), hyphens, and non-interior underscores.
394
395 You can also use negation in both "\p{}" and "\P{}" by introducing a
396 caret ("^") between the first brace and the property name: "\p{^Tamil}"
397 is equal to "\P{Tamil}".
398
399 Almost all properties are immune to case-insensitive matching. That
400 is, adding a "/i" regular expression modifier does not change what they
401 match. There are two sets that are affected. The first set is
402 "Uppercase_Letter", "Lowercase_Letter", and "Titlecase_Letter", all of
403 which match "Cased_Letter" under "/i" matching. And the second set is
404 "Uppercase", "Lowercase", and "Titlecase", all of which match "Cased"
405 under "/i" matching. This set also includes its subsets "PosixUpper"
406 and "PosixLower" both of which under "/i" match "PosixAlpha". (The
407 difference between these sets is that some things, such as Roman
408 numerals, come in both upper and lower case so they are "Cased", but
409 aren't considered letters, so they aren't "Cased_Letter"'s.)
410
411 See "Beyond Unicode code points" for special considerations when
412 matching Unicode properties against non-Unicode code points.
413
414 General_Category
415
416 Every Unicode character is assigned a general category, which is the
417 "most usual categorization of a character" (from
418 <http://www.unicode.org/reports/tr44>).
419
420 The compound way of writing these is like "\p{General_Category=Number}"
421 (short: "\p{gc:n}"). But Perl furnishes shortcuts in which everything
422 up through the equal or colon separator is omitted. So you can instead
423 just write "\pN".
424
425 Here are the short and long forms of the values the "General Category"
426 property can have:
427
428 Short Long
429
430 L Letter
431 LC, L& Cased_Letter (that is: [\p{Ll}\p{Lu}\p{Lt}])
432 Lu Uppercase_Letter
433 Ll Lowercase_Letter
434 Lt Titlecase_Letter
435 Lm Modifier_Letter
436 Lo Other_Letter
437
438 M Mark
439 Mn Nonspacing_Mark
440 Mc Spacing_Mark
441 Me Enclosing_Mark
442
443 N Number
444 Nd Decimal_Number (also Digit)
445 Nl Letter_Number
446 No Other_Number
447
448 P Punctuation (also Punct)
449 Pc Connector_Punctuation
450 Pd Dash_Punctuation
451 Ps Open_Punctuation
452 Pe Close_Punctuation
453 Pi Initial_Punctuation
454 (may behave like Ps or Pe depending on usage)
455 Pf Final_Punctuation
456 (may behave like Ps or Pe depending on usage)
457 Po Other_Punctuation
458
459 S Symbol
460 Sm Math_Symbol
461 Sc Currency_Symbol
462 Sk Modifier_Symbol
463 So Other_Symbol
464
465 Z Separator
466 Zs Space_Separator
467 Zl Line_Separator
468 Zp Paragraph_Separator
469
470 C Other
471 Cc Control (also Cntrl)
472 Cf Format
473 Cs Surrogate
474 Co Private_Use
475 Cn Unassigned
476
477 Single-letter properties match all characters in any of the two-letter
478 sub-properties starting with the same letter. "LC" and "L&" are
479 special: both are aliases for the set consisting of everything matched
480 by "Ll", "Lu", and "Lt".
481
482 Bidirectional Character Types
483
484 Because scripts differ in their directionality (Hebrew and Arabic are
485 written right to left, for example) Unicode supplies a "Bidi_Class"
486 property. Some of the values this property can have are:
487
488 Value Meaning
489
490 L Left-to-Right
491 LRE Left-to-Right Embedding
492 LRO Left-to-Right Override
493 R Right-to-Left
494 AL Arabic Letter
495 RLE Right-to-Left Embedding
496 RLO Right-to-Left Override
497 PDF Pop Directional Format
498 EN European Number
499 ES European Separator
500 ET European Terminator
501 AN Arabic Number
502 CS Common Separator
503 NSM Non-Spacing Mark
504 BN Boundary Neutral
505 B Paragraph Separator
506 S Segment Separator
507 WS Whitespace
508 ON Other Neutrals
509
510 This property is always written in the compound form. For example,
511 "\p{Bidi_Class:R}" matches characters that are normally written right
512 to left. Unlike the "General_Category" property, this property can
513 have more values added in a future Unicode release. Those listed above
514 comprised the complete set for many Unicode releases, but others were
515 added in Unicode 6.3; you can always find what the current ones are in
516 perluniprops. And <http://www.unicode.org/reports/tr9/> describes how
517 to use them.
518
519 Scripts
520
521 The world's languages are written in many different scripts. This
522 sentence (unless you're reading it in translation) is written in Latin,
523 while Russian is written in Cyrillic, and Greek is written in, well,
524 Greek; Japanese mainly in Hiragana or Katakana. There are many more.
525
526 The Unicode "Script" and "Script_Extensions" properties give what
527 script a given character is in. The "Script_Extensions" property is an
528 improved version of "Script", as demonstrated below. Either property
529 can be specified with the compound form like "\p{Script=Hebrew}"
530 (short: "\p{sc=hebr}"), or "\p{Script_Extensions=Javanese}" (short:
531 "\p{scx=java}"). In addition, Perl furnishes shortcuts for all
532 "Script_Extensions" property names. You can omit everything up through
533 the equals (or colon), and simply write "\p{Latin}" or "\P{Cyrillic}".
534 (This is not true for "Script", which is required to be written in the
535 compound form. Prior to Perl v5.26, the single form returned the plain
536 old "Script" version, but was changed because "Script_Extensions" gives
537 better results.)
538
539 The difference between these two properties involves characters that
540 are used in multiple scripts. For example the digits '0' through '9'
541 are used in many parts of the world. These are placed in a script
542 named "Common". Other characters are used in just a few scripts. For
543 example, the "KATAKANA-HIRAGANA DOUBLE HYPHEN" is used in both Japanese
544 scripts, Katakana and Hiragana, but nowhere else. The "Script"
545 property places all characters that are used in multiple scripts in the
546 "Common" script, while the "Script_Extensions" property places those
547 that are used in only a few scripts into each of those scripts; while
548 still using "Common" for those used in many scripts. Thus both these
549 match:
550
551 "0" =~ /\p{sc=Common}/ # Matches
552 "0" =~ /\p{scx=Common}/ # Matches
553
554 and only the first of these match:
555
556 "\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{sc=Common} # Matches
557 "\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{scx=Common} # No match
558
559 And only the last two of these match:
560
561 "\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{sc=Hiragana} # No match
562 "\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{sc=Katakana} # No match
563 "\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{scx=Hiragana} # Matches
564 "\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{scx=Katakana} # Matches
565
566 "Script_Extensions" is thus an improved "Script", in which there are
567 fewer characters in the "Common" script, and correspondingly more in
568 other scripts. It is new in Unicode version 6.0, and its data are
569 likely to change significantly in later releases, as things get sorted
570 out. New code should probably be using "Script_Extensions" and not
571 plain "Script". If you compile perl with a Unicode release that
572 doesn't have "Script_Extensions", the single form Perl extensions will
573 instead refer to the plain "Script" property. If you compile with a
574 version of Unicode that doesn't have the "Script" property, these
575 extensions will not be defined at all.
576
577 (Actually, besides "Common", the "Inherited" script, contains
578 characters that are used in multiple scripts. These are modifier
579 characters which inherit the script value of the controlling character.
580 Some of these are used in many scripts, and so go into "Inherited" in
581 both "Script" and "Script_Extensions". Others are used in just a few
582 scripts, so are in "Inherited" in "Script", but not in
583 "Script_Extensions".)
584
585 It is worth stressing that there are several different sets of digits
586 in Unicode that are equivalent to 0-9 and are matchable by "\d" in a
587 regular expression. If they are used in a single language only, they
588 are in that language's "Script" and "Script_Extensions". If they are
589 used in more than one script, they will be in "sc=Common", but only if
590 they are used in many scripts should they be in "scx=Common".
591
592 The explanation above has omitted some detail; refer to UAX#24 "Unicode
593 Script Property": <http://www.unicode.org/reports/tr24>.
594
595 A complete list of scripts and their shortcuts is in perluniprops.
596
597 Use of the "Is" Prefix
598
599 For backward compatibility (with Perl 5.6), all properties writable
600 without using the compound form mentioned so far may have "Is" or "Is_"
601 prepended to their name, so "\P{Is_Lu}", for example, is equal to
602 "\P{Lu}", and "\p{IsScript:Arabic}" is equal to "\p{Arabic}".
603
604 Blocks
605
606 In addition to scripts, Unicode also defines blocks of characters. The
607 difference between scripts and blocks is that the concept of scripts is
608 closer to natural languages, while the concept of blocks is more of an
609 artificial grouping based on groups of Unicode characters with
610 consecutive ordinal values. For example, the "Basic Latin" block is all
611 the characters whose ordinals are between 0 and 127, inclusive; in
612 other words, the ASCII characters. The "Latin" script contains some
613 letters from this as well as several other blocks, like "Latin-1
614 Supplement", "Latin Extended-A", etc., but it does not contain all the
615 characters from those blocks. It does not, for example, contain the
616 digits 0-9, because those digits are shared across many scripts, and
617 hence are in the "Common" script.
618
619 For more about scripts versus blocks, see UAX#24 "Unicode Script
620 Property": <http://www.unicode.org/reports/tr24>
621
622 The "Script_Extensions" or "Script" properties are likely to be the
623 ones you want to use when processing natural language; the "Block"
624 property may occasionally be useful in working with the nuts and bolts
625 of Unicode.
626
627 Block names are matched in the compound form, like "\p{Block: Arrows}"
628 or "\p{Blk=Hebrew}". Unlike most other properties, only a few block
629 names have a Unicode-defined short name.
630
631 Perl also defines single form synonyms for the block property in cases
632 where these do not conflict with something else. But don't use any of
633 these, because they are unstable. Since these are Perl extensions,
634 they are subordinate to official Unicode property names; Unicode
635 doesn't know nor care about Perl's extensions. It may happen that a
636 name that currently means the Perl extension will later be changed
637 without warning to mean a different Unicode property in a future
638 version of the perl interpreter that uses a later Unicode release, and
639 your code would no longer work. The extensions are mentioned here for
640 completeness: Take the block name and prefix it with one of: "In" (for
641 example "\p{Blk=Arrows}" can currently be written as "\p{In_Arrows}");
642 or sometimes "Is" (like "\p{Is_Arrows}"); or sometimes no prefix at all
643 ("\p{Arrows}"). As of this writing (Unicode 9.0) there are no
644 conflicts with using the "In_" prefix, but there are plenty with the
645 other two forms. For example, "\p{Is_Hebrew}" and "\p{Hebrew}" mean
646 "\p{Script_Extensions=Hebrew}" which is NOT the same thing as
647 "\p{Blk=Hebrew}". Our advice used to be to use the "In_" prefix as a
648 single form way of specifying a block. But Unicode 8.0 added
649 properties whose names begin with "In", and it's now clear that it's
650 only luck that's so far prevented a conflict. Using "In" is only
651 marginally less typing than "Blk:", and the latter's meaning is clearer
652 anyway, and guaranteed to never conflict. So don't take chances. Use
653 "\p{Blk=foo}" for new code. And be sure that block is what you really
654 really want to do. In most cases scripts are what you want instead.
655
656 A complete list of blocks is in perluniprops.
657
658 Other Properties
659
660 There are many more properties than the very basic ones described here.
661 A complete list is in perluniprops.
662
663 Unicode defines all its properties in the compound form, so all single-
664 form properties are Perl extensions. Most of these are just synonyms
665 for the Unicode ones, but some are genuine extensions, including
666 several that are in the compound form. And quite a few of these are
667 actually recommended by Unicode (in
668 <http://www.unicode.org/reports/tr18>).
669
670 This section gives some details on all extensions that aren't just
671 synonyms for compound-form Unicode properties (for those properties,
672 you'll have to refer to the Unicode Standard
673 <http://www.unicode.org/reports/tr44>.
674
675 "\p{All}"
676 This matches every possible code point. It is equivalent to
677 "qr/./s". Unlike all the other non-user-defined "\p{}" property
678 matches, no warning is ever generated if this is property is
679 matched against a non-Unicode code point (see "Beyond Unicode code
680 points" below).
681
682 "\p{Alnum}"
683 This matches any "\p{Alphabetic}" or "\p{Decimal_Number}"
684 character.
685
686 "\p{Any}"
687 This matches any of the 1_114_112 Unicode code points. It is a
688 synonym for "\p{Unicode}".
689
690 "\p{ASCII}"
691 This matches any of the 128 characters in the US-ASCII character
692 set, which is a subset of Unicode.
693
694 "\p{Assigned}"
695 This matches any assigned code point; that is, any code point whose
696 general category is not "Unassigned" (or equivalently, not "Cn").
697
698 "\p{Blank}"
699 This is the same as "\h" and "\p{HorizSpace}": A character that
700 changes the spacing horizontally.
701
702 "\p{Decomposition_Type: Non_Canonical}" (Short: "\p{Dt=NonCanon}")
703 Matches a character that has a non-canonical decomposition.
704
705 The "Extended Grapheme Clusters (Logical characters)" section above
706 talked about canonical decompositions. However, many more
707 characters have a different type of decomposition, a "compatible"
708 or "non-canonical" decomposition. The sequences that form these
709 decompositions are not considered canonically equivalent to the
710 pre-composed character. An example is the "SUPERSCRIPT ONE". It
711 is somewhat like a regular digit 1, but not exactly; its
712 decomposition into the digit 1 is called a "compatible"
713 decomposition, specifically a "super" decomposition. There are
714 several such compatibility decompositions (see
715 <http://www.unicode.org/reports/tr44>), including one called
716 "compat", which means some miscellaneous type of decomposition that
717 doesn't fit into the other decomposition categories that Unicode
718 has chosen.
719
720 Note that most Unicode characters don't have a decomposition, so
721 their decomposition type is "None".
722
723 For your convenience, Perl has added the "Non_Canonical"
724 decomposition type to mean any of the several compatibility
725 decompositions.
726
727 "\p{Graph}"
728 Matches any character that is graphic. Theoretically, this means a
729 character that on a printer would cause ink to be used.
730
731 "\p{HorizSpace}"
732 This is the same as "\h" and "\p{Blank}": a character that changes
733 the spacing horizontally.
734
735 "\p{In=*}"
736 This is a synonym for "\p{Present_In=*}"
737
738 "\p{PerlSpace}"
739 This is the same as "\s", restricted to ASCII, namely "[ \f\n\r\t]"
740 and starting in Perl v5.18, a vertical tab.
741
742 Mnemonic: Perl's (original) space
743
744 "\p{PerlWord}"
745 This is the same as "\w", restricted to ASCII, namely
746 "[A-Za-z0-9_]"
747
748 Mnemonic: Perl's (original) word.
749
750 "\p{Posix...}"
751 There are several of these, which are equivalents, using the "\p{}"
752 notation, for Posix classes and are described in "POSIX Character
753 Classes" in perlrecharclass.
754
755 "\p{Present_In: *}" (Short: "\p{In=*}")
756 This property is used when you need to know in what Unicode
757 version(s) a character is.
758
759 The "*" above stands for some two digit Unicode version number,
760 such as 1.1 or 4.0; or the "*" can also be "Unassigned". This
761 property will match the code points whose final disposition has
762 been settled as of the Unicode release given by the version number;
763 "\p{Present_In: Unassigned}" will match those code points whose
764 meaning has yet to be assigned.
765
766 For example, "U+0041" "LATIN CAPITAL LETTER A" was present in the
767 very first Unicode release available, which is 1.1, so this
768 property is true for all valid "*" versions. On the other hand,
769 "U+1EFF" was not assigned until version 5.1 when it became "LATIN
770 SMALL LETTER Y WITH LOOP", so the only "*" that would match it are
771 5.1, 5.2, and later.
772
773 Unicode furnishes the "Age" property from which this is derived.
774 The problem with Age is that a strict interpretation of it (which
775 Perl takes) has it matching the precise release a code point's
776 meaning is introduced in. Thus "U+0041" would match only 1.1; and
777 "U+1EFF" only 5.1. This is not usually what you want.
778
779 Some non-Perl implementations of the Age property may change its
780 meaning to be the same as the Perl "Present_In" property; just be
781 aware of that.
782
783 Another confusion with both these properties is that the definition
784 is not that the code point has been assigned, but that the meaning
785 of the code point has been determined. This is because 66 code
786 points will always be unassigned, and so the "Age" for them is the
787 Unicode version in which the decision to make them so was made.
788 For example, "U+FDD0" is to be permanently unassigned to a
789 character, and the decision to do that was made in version 3.1, so
790 "\p{Age=3.1}" matches this character, as also does "\p{Present_In:
791 3.1}" and up.
792
793 "\p{Print}"
794 This matches any character that is graphical or blank, except
795 controls.
796
797 "\p{SpacePerl}"
798 This is the same as "\s", including beyond ASCII.
799
800 Mnemonic: Space, as modified by Perl. (It doesn't include the
801 vertical tab until v5.18, which both the Posix standard and Unicode
802 consider white space.)
803
804 "\p{Title}" and "\p{Titlecase}"
805 Under case-sensitive matching, these both match the same code
806 points as "\p{General Category=Titlecase_Letter}" ("\p{gc=lt}").
807 The difference is that under "/i" caseless matching, these match
808 the same as "\p{Cased}", whereas "\p{gc=lt}" matches
809 "\p{Cased_Letter").
810
811 "\p{Unicode}"
812 This matches any of the 1_114_112 Unicode code points. "\p{Any}".
813
814 "\p{VertSpace}"
815 This is the same as "\v": A character that changes the spacing
816 vertically.
817
818 "\p{Word}"
819 This is the same as "\w", including over 100_000 characters beyond
820 ASCII.
821
822 "\p{XPosix...}"
823 There are several of these, which are the standard Posix classes
824 extended to the full Unicode range. They are described in "POSIX
825 Character Classes" in perlrecharclass.
826
827 User-Defined Character Properties
828 You can define your own binary character properties by defining
829 subroutines whose names begin with "In" or "Is". (The experimental
830 feature "(?[ ])" in perlre provides an alternative which allows more
831 complex definitions.) The subroutines can be defined in any package.
832 The user-defined properties can be used in the regular expression
833 "\p{}" and "\P{}" constructs; if you are using a user-defined property
834 from a package other than the one you are in, you must specify its
835 package in the "\p{}" or "\P{}" construct.
836
837 # assuming property Is_Foreign defined in Lang::
838 package main; # property package name required
839 if ($txt =~ /\p{Lang::IsForeign}+/) { ... }
840
841 package Lang; # property package name not required
842 if ($txt =~ /\p{IsForeign}+/) { ... }
843
844 Note that the effect is compile-time and immutable once defined.
845 However, the subroutines are passed a single parameter, which is 0 if
846 case-sensitive matching is in effect and non-zero if caseless matching
847 is in effect. The subroutine may return different values depending on
848 the value of the flag, and one set of values will immutably be in
849 effect for all case-sensitive matches, and the other set for all case-
850 insensitive matches.
851
852 Note that if the regular expression is tainted, then Perl will die
853 rather than calling the subroutine when the name of the subroutine is
854 determined by the tainted data.
855
856 The subroutines must return a specially-formatted string, with one or
857 more newline-separated lines. Each line must be one of the following:
858
859 · A single hexadecimal number denoting a code point to include.
860
861 · Two hexadecimal numbers separated by horizontal whitespace (space
862 or tabular characters) denoting a range of code points to include.
863
864 · Something to include, prefixed by "+": a built-in character
865 property (prefixed by "utf8::") or a fully qualified (including
866 package name) user-defined character property, to represent all the
867 characters in that property; two hexadecimal code points for a
868 range; or a single hexadecimal code point.
869
870 · Something to exclude, prefixed by "-": an existing character
871 property (prefixed by "utf8::") or a fully qualified (including
872 package name) user-defined character property, to represent all the
873 characters in that property; two hexadecimal code points for a
874 range; or a single hexadecimal code point.
875
876 · Something to negate, prefixed "!": an existing character property
877 (prefixed by "utf8::") or a fully qualified (including package
878 name) user-defined character property, to represent all the
879 characters in that property; two hexadecimal code points for a
880 range; or a single hexadecimal code point.
881
882 · Something to intersect with, prefixed by "&": an existing character
883 property (prefixed by "utf8::") or a fully qualified (including
884 package name) user-defined character property, for all the
885 characters except the characters in the property; two hexadecimal
886 code points for a range; or a single hexadecimal code point.
887
888 For example, to define a property that covers both the Japanese
889 syllabaries (hiragana and katakana), you can define
890
891 sub InKana {
892 return <<END;
893 3040\t309F
894 30A0\t30FF
895 END
896 }
897
898 Imagine that the here-doc end marker is at the beginning of the line.
899 Now you can use "\p{InKana}" and "\P{InKana}".
900
901 You could also have used the existing block property names:
902
903 sub InKana {
904 return <<'END';
905 +utf8::InHiragana
906 +utf8::InKatakana
907 END
908 }
909
910 Suppose you wanted to match only the allocated characters, not the raw
911 block ranges: in other words, you want to remove the unassigned
912 characters:
913
914 sub InKana {
915 return <<'END';
916 +utf8::InHiragana
917 +utf8::InKatakana
918 -utf8::IsCn
919 END
920 }
921
922 The negation is useful for defining (surprise!) negated classes.
923
924 sub InNotKana {
925 return <<'END';
926 !utf8::InHiragana
927 -utf8::InKatakana
928 +utf8::IsCn
929 END
930 }
931
932 This will match all non-Unicode code points, since every one of them is
933 not in Kana. You can use intersection to exclude these, if desired, as
934 this modified example shows:
935
936 sub InNotKana {
937 return <<'END';
938 !utf8::InHiragana
939 -utf8::InKatakana
940 +utf8::IsCn
941 &utf8::Any
942 END
943 }
944
945 &utf8::Any must be the last line in the definition.
946
947 Intersection is used generally for getting the common characters
948 matched by two (or more) classes. It's important to remember not to
949 use "&" for the first set; that would be intersecting with nothing,
950 resulting in an empty set.
951
952 Unlike non-user-defined "\p{}" property matches, no warning is ever
953 generated if these properties are matched against a non-Unicode code
954 point (see "Beyond Unicode code points" below).
955
956 User-Defined Case Mappings (for serious hackers only)
957 This feature has been removed as of Perl 5.16. The CPAN module
958 "Unicode::Casing" provides better functionality without the drawbacks
959 that this feature had. If you are using a Perl earlier than 5.16, this
960 feature was most fully documented in the 5.14 version of this pod:
961 <http://perldoc.perl.org/5.14.0/perlunicode.html#User-Defined-Case-Mappings-%28for-serious-hackers-only%29>
962
963 Character Encodings for Input and Output
964 See Encode.
965
966 Unicode Regular Expression Support Level
967 The following list of Unicode supported features for regular
968 expressions describes all features currently directly supported by core
969 Perl. The references to "Level N" and the section numbers refer to
970 UTS#18 "Unicode Regular Expressions"
971 <http://www.unicode.org/reports/tr18>, version 13, November 2013.
972
973 Level 1 - Basic Unicode Support
974
975 RL1.1 Hex Notation - Done [1]
976 RL1.2 Properties - Done [2]
977 RL1.2a Compatibility Properties - Done [3]
978 RL1.3 Subtraction and Intersection - Experimental [4]
979 RL1.4 Simple Word Boundaries - Done [5]
980 RL1.5 Simple Loose Matches - Done [6]
981 RL1.6 Line Boundaries - Partial [7]
982 RL1.7 Supplementary Code Points - Done [8]
983
984 [1] "\N{U+...}" and "\x{...}"
985 [2] "\p{...}" "\P{...}". This requirement is for a minimal list of
986 properties. Perl supports these and all other Unicode character
987 properties, as R2.7 asks (see "Unicode Character Properties" above).
988 [3] Perl has "\d" "\D" "\s" "\S" "\w" "\W" "\X" "[:prop:]" "[:^prop:]",
989 plus all the properties specified by
990 <http://www.unicode.org/reports/tr18/#Compatibility_Properties>. These
991 are described above in "Other Properties"
992 [4] The experimental feature "(?[...])" starting in v5.18 accomplishes
993 this.
994
995 See "(?[ ])" in perlre. If you don't want to use an experimental
996 feature, you can use one of the following:
997
998 · Regular expression lookahead
999
1000 You can mimic class subtraction using lookahead. For example,
1001 what UTS#18 might write as
1002
1003 [{Block=Greek}-[{UNASSIGNED}]]
1004
1005 in Perl can be written as:
1006
1007 (?!\p{Unassigned})\p{Block=Greek}
1008 (?=\p{Assigned})\p{Block=Greek}
1009
1010 But in this particular example, you probably really want
1011
1012 \p{Greek}
1013
1014 which will match assigned characters known to be part of the
1015 Greek script.
1016
1017 · CPAN module "Unicode::Regex::Set"
1018
1019 It does implement the full UTS#18 grouping, intersection,
1020 union, and removal (subtraction) syntax.
1021
1022 · "User-Defined Character Properties"
1023
1024 "+" for union, "-" for removal (set-difference), "&" for
1025 intersection
1026
1027 [5] "\b" "\B" meet most, but not all, the details of this requirement,
1028 but "\b{wb}" and "\B{wb}" do, as well as the stricter R2.3.
1029 [6] Note that Perl does Full case-folding in matching, not Simple:
1030
1031 For example "U+1F88" is equivalent to "U+1F00 U+03B9", instead of
1032 just "U+1F80". This difference matters mainly for certain Greek
1033 capital letters with certain modifiers: the Full case-folding
1034 decomposes the letter, while the Simple case-folding would map it
1035 to a single character.
1036
1037 [7] The reason this is considered to be only partially implemented is
1038 that Perl has "qr/\b{lb}/" and "Unicode::LineBreak" that are
1039 conformant with UAX#14 "Unicode Line Breaking Algorithm"
1040 <http://www.unicode.org/reports/tr14>. The regular expression
1041 construct provides default behavior, while the heavier-weight
1042 module provides customizable line breaking.
1043
1044 But Perl treats "\n" as the start- and end-line delimiter, whereas
1045 Unicode specifies more characters that should be so-interpreted.
1046
1047 These are:
1048
1049 VT U+000B (\v in C)
1050 FF U+000C (\f)
1051 CR U+000D (\r)
1052 NEL U+0085
1053 LS U+2028
1054 PS U+2029
1055
1056 "^" and "$" in regular expression patterns are supposed to match
1057 all these, but don't. These characters also don't, but should,
1058 affect "<>" $., and script line numbers.
1059
1060 Also, lines should not be split within "CRLF" (i.e. there is no
1061 empty line between "\r" and "\n"). For "CRLF", try the ":crlf"
1062 layer (see PerlIO).
1063
1064 [8] UTF-8/UTF-EBDDIC used in Perl allows not only "U+10000" to
1065 "U+10FFFF" but also beyond "U+10FFFF"
1066
1067 Level 2 - Extended Unicode Support
1068
1069 RL2.1 Canonical Equivalents - Retracted [9]
1070 by Unicode
1071 RL2.2 Extended Grapheme Clusters - Partial [10]
1072 RL2.3 Default Word Boundaries - Done [11]
1073 RL2.4 Default Case Conversion - Done
1074 RL2.5 Name Properties - Done
1075 RL2.6 Wildcard Properties - Missing
1076 RL2.7 Full Properties - Done
1077
1078 [9] Unicode has rewritten this portion of UTS#18 to say that getting
1079 canonical equivalence (see UAX#15 "Unicode Normalization Forms"
1080 <http://www.unicode.org/reports/tr15>) is basically to be done at the
1081 programmer level. Use NFD to write both your regular expressions and
1082 text to match them against (you can use Unicode::Normalize).
1083 [10] Perl has "\X" and "\b{gcb}" but we don't have a "Grapheme Cluster
1084 Mode".
1085 [11] see UAX#29 "Unicode Text Segmentation"
1086 <http://www.unicode.org/reports/tr29>,
1087
1088 Level 3 - Tailored Support
1089
1090 RL3.1 Tailored Punctuation - Missing
1091 RL3.2 Tailored Grapheme Clusters - Missing [12]
1092 RL3.3 Tailored Word Boundaries - Missing
1093 RL3.4 Tailored Loose Matches - Retracted by Unicode
1094 RL3.5 Tailored Ranges - Retracted by Unicode
1095 RL3.6 Context Matching - Missing [13]
1096 RL3.7 Incremental Matches - Missing
1097 RL3.8 Unicode Set Sharing - Unicode is proposing
1098 to retract this
1099 RL3.9 Possible Match Sets - Missing
1100 RL3.10 Folded Matching - Retracted by Unicode
1101 RL3.11 Submatchers - Missing
1102
1103 [12] Perl has Unicode::Collate, but it isn't integrated with regular
1104 expressions. See UTS#10 "Unicode Collation Algorithms"
1105 <http://www.unicode.org/reports/tr10>.
1106 [13] Perl has "(?<=x)" and "(?=x)", but lookaheads or lookbehinds
1107 should see outside of the target substring
1108
1109 Unicode Encodings
1110 Unicode characters are assigned to code points, which are abstract
1111 numbers. To use these numbers, various encodings are needed.
1112
1113 · UTF-8
1114
1115 UTF-8 is a variable-length (1 to 4 bytes), byte-order independent
1116 encoding. In most of Perl's documentation, including elsewhere in
1117 this document, the term "UTF-8" means also "UTF-EBCDIC". But in
1118 this section, "UTF-8" refers only to the encoding used on ASCII
1119 platforms. It is a superset of 7-bit US-ASCII, so anything encoded
1120 in ASCII has the identical representation when encoded in UTF-8.
1121
1122 The following table is from Unicode 3.2.
1123
1124 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
1125
1126 U+0000..U+007F 00..7F
1127 U+0080..U+07FF * C2..DF 80..BF
1128 U+0800..U+0FFF E0 * A0..BF 80..BF
1129 U+1000..U+CFFF E1..EC 80..BF 80..BF
1130 U+D000..U+D7FF ED 80..9F 80..BF
1131 U+D800..U+DFFF +++++ utf16 surrogates, not legal utf8 +++++
1132 U+E000..U+FFFF EE..EF 80..BF 80..BF
1133 U+10000..U+3FFFF F0 * 90..BF 80..BF 80..BF
1134 U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
1135 U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
1136
1137 Note the gaps marked by "*" before several of the byte entries
1138 above. These are caused by legal UTF-8 avoiding non-shortest
1139 encodings: it is technically possible to UTF-8-encode a single code
1140 point in different ways, but that is explicitly forbidden, and the
1141 shortest possible encoding should always be used (and that is what
1142 Perl does).
1143
1144 Another way to look at it is via bits:
1145
1146 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
1147
1148 0aaaaaaa 0aaaaaaa
1149 00000bbbbbaaaaaa 110bbbbb 10aaaaaa
1150 ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
1151 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa
1152
1153 As you can see, the continuation bytes all begin with "10", and the
1154 leading bits of the start byte tell how many bytes there are in the
1155 encoded character.
1156
1157 The original UTF-8 specification allowed up to 6 bytes, to allow
1158 encoding of numbers up to "0x7FFF_FFFF". Perl continues to allow
1159 those, and has extended that up to 13 bytes to encode code points
1160 up to what can fit in a 64-bit word. However, Perl will warn if
1161 you output any of these as being non-portable; and under strict
1162 UTF-8 input protocols, they are forbidden. In addition, it is
1163 deprecated to use a code point larger than what a signed integer
1164 variable on your system can hold. On 32-bit ASCII systems, this
1165 means "0x7FFF_FFFF" is the legal maximum going forward (much higher
1166 on 64-bit systems).
1167
1168 · UTF-EBCDIC
1169
1170 Like UTF-8, but EBCDIC-safe, in the way that UTF-8 is ASCII-safe.
1171 This means that all the basic characters (which includes all those
1172 that have ASCII equivalents (like "A", "0", "%", etc.) are the
1173 same in both EBCDIC and UTF-EBCDIC.)
1174
1175 UTF-EBCDIC is used on EBCDIC platforms. It generally requires more
1176 bytes to represent a given code point than UTF-8 does; the largest
1177 Unicode code points take 5 bytes to represent (instead of 4 in
1178 UTF-8), and, extended for 64-bit words, it uses 14 bytes instead of
1179 13 bytes in UTF-8.
1180
1181 · UTF-16, UTF-16BE, UTF-16LE, Surrogates, and "BOM"'s (Byte Order
1182 Marks)
1183
1184 The followings items are mostly for reference and general Unicode
1185 knowledge, Perl doesn't use these constructs internally.
1186
1187 Like UTF-8, UTF-16 is a variable-width encoding, but where UTF-8
1188 uses 8-bit code units, UTF-16 uses 16-bit code units. All code
1189 points occupy either 2 or 4 bytes in UTF-16: code points
1190 "U+0000..U+FFFF" are stored in a single 16-bit unit, and code
1191 points "U+10000..U+10FFFF" in two 16-bit units. The latter case is
1192 using surrogates, the first 16-bit unit being the high surrogate,
1193 and the second being the low surrogate.
1194
1195 Surrogates are code points set aside to encode the
1196 "U+10000..U+10FFFF" range of Unicode code points in pairs of 16-bit
1197 units. The high surrogates are the range "U+D800..U+DBFF" and the
1198 low surrogates are the range "U+DC00..U+DFFF". The surrogate
1199 encoding is
1200
1201 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
1202 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
1203
1204 and the decoding is
1205
1206 $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
1207
1208 Because of the 16-bitness, UTF-16 is byte-order dependent. UTF-16
1209 itself can be used for in-memory computations, but if storage or
1210 transfer is required either UTF-16BE (big-endian) or UTF-16LE
1211 (little-endian) encodings must be chosen.
1212
1213 This introduces another problem: what if you just know that your
1214 data is UTF-16, but you don't know which endianness? Byte Order
1215 Marks, or "BOM"'s, are a solution to this. A special character has
1216 been reserved in Unicode to function as a byte order marker: the
1217 character with the code point "U+FEFF" is the "BOM".
1218
1219 The trick is that if you read a "BOM", you will know the byte
1220 order, since if it was written on a big-endian platform, you will
1221 read the bytes "0xFE 0xFF", but if it was written on a little-
1222 endian platform, you will read the bytes "0xFF 0xFE". (And if the
1223 originating platform was writing in ASCII platform UTF-8, you will
1224 read the bytes "0xEF 0xBB 0xBF".)
1225
1226 The way this trick works is that the character with the code point
1227 "U+FFFE" is not supposed to be in input streams, so the sequence of
1228 bytes "0xFF 0xFE" is unambiguously ""BOM", represented in little-
1229 endian format" and cannot be "U+FFFE", represented in big-endian
1230 format".
1231
1232 Surrogates have no meaning in Unicode outside their use in pairs to
1233 represent other code points. However, Perl allows them to be
1234 represented individually internally, for example by saying
1235 "chr(0xD801)", so that all code points, not just those valid for
1236 open interchange, are representable. Unicode does define semantics
1237 for them, such as their "General_Category" is "Cs". But because
1238 their use is somewhat dangerous, Perl will warn (using the warning
1239 category "surrogate", which is a sub-category of "utf8") if an
1240 attempt is made to do things like take the lower case of one, or
1241 match case-insensitively, or to output them. (But don't try this
1242 on Perls before 5.14.)
1243
1244 · UTF-32, UTF-32BE, UTF-32LE
1245
1246 The UTF-32 family is pretty much like the UTF-16 family, except
1247 that the units are 32-bit, and therefore the surrogate scheme is
1248 not needed. UTF-32 is a fixed-width encoding. The "BOM"
1249 signatures are "0x00 0x00 0xFE 0xFF" for BE and "0xFF 0xFE 0x00
1250 0x00" for LE.
1251
1252 · UCS-2, UCS-4
1253
1254 Legacy, fixed-width encodings defined by the ISO 10646 standard.
1255 UCS-2 is a 16-bit encoding. Unlike UTF-16, UCS-2 is not extensible
1256 beyond "U+FFFF", because it does not use surrogates. UCS-4 is a
1257 32-bit encoding, functionally identical to UTF-32 (the difference
1258 being that UCS-4 forbids neither surrogates nor code points larger
1259 than "0x10_FFFF").
1260
1261 · UTF-7
1262
1263 A seven-bit safe (non-eight-bit) encoding, which is useful if the
1264 transport or storage is not eight-bit safe. Defined by RFC 2152.
1265
1266 Noncharacter code points
1267 66 code points are set aside in Unicode as "noncharacter code points".
1268 These all have the "Unassigned" ("Cn") "General_Category", and no
1269 character will ever be assigned to any of them. They are the 32 code
1270 points between "U+FDD0" and "U+FDEF" inclusive, and the 34 code points:
1271
1272 U+FFFE U+FFFF
1273 U+1FFFE U+1FFFF
1274 U+2FFFE U+2FFFF
1275 ...
1276 U+EFFFE U+EFFFF
1277 U+FFFFE U+FFFFF
1278 U+10FFFE U+10FFFF
1279
1280 Until Unicode 7.0, the noncharacters were "forbidden for use in open
1281 interchange of Unicode text data", so that code that processed those
1282 streams could use these code points as sentinels that could be mixed in
1283 with character data, and would always be distinguishable from that
1284 data. (Emphasis above and in the next paragraph are added in this
1285 document.)
1286
1287 Unicode 7.0 changed the wording so that they are "not recommended for
1288 use in open interchange of Unicode text data". The 7.0 Standard goes
1289 on to say:
1290
1291 "If a noncharacter is received in open interchange, an application
1292 is not required to interpret it in any way. It is good practice,
1293 however, to recognize it as a noncharacter and to take appropriate
1294 action, such as replacing it with "U+FFFD" replacement character,
1295 to indicate the problem in the text. It is not recommended to
1296 simply delete noncharacter code points from such text, because of
1297 the potential security issues caused by deleting uninterpreted
1298 characters. (See conformance clause C7 in Section 3.2, Conformance
1299 Requirements, and Unicode Technical Report #36, "Unicode Security
1300 Considerations"
1301 <http://www.unicode.org/reports/tr36/#Substituting_for_Ill_Formed_Subsequences>)."
1302
1303 This change was made because it was found that various commercial tools
1304 like editors, or for things like source code control, had been written
1305 so that they would not handle program files that used these code
1306 points, effectively precluding their use almost entirely! And that was
1307 never the intent. They've always been meant to be usable within an
1308 application, or cooperating set of applications, at will.
1309
1310 If you're writing code, such as an editor, that is supposed to be able
1311 to handle any Unicode text data, then you shouldn't be using these code
1312 points yourself, and instead allow them in the input. If you need
1313 sentinels, they should instead be something that isn't legal Unicode.
1314 For UTF-8 data, you can use the bytes 0xC1 and 0xC2 as sentinels, as
1315 they never appear in well-formed UTF-8. (There are equivalents for
1316 UTF-EBCDIC). You can also store your Unicode code points in integer
1317 variables and use negative values as sentinels.
1318
1319 If you're not writing such a tool, then whether you accept
1320 noncharacters as input is up to you (though the Standard recommends
1321 that you not). If you do strict input stream checking with Perl, these
1322 code points continue to be forbidden. This is to maintain backward
1323 compatibility (otherwise potential security holes could open up, as an
1324 unsuspecting application that was written assuming the noncharacters
1325 would be filtered out before getting to it, could now, without warning,
1326 start getting them). To do strict checking, you can use the layer
1327 ":encoding('UTF-8')".
1328
1329 Perl continues to warn (using the warning category "nonchar", which is
1330 a sub-category of "utf8") if an attempt is made to output
1331 noncharacters.
1332
1333 Beyond Unicode code points
1334 The maximum Unicode code point is "U+10FFFF", and Unicode only defines
1335 operations on code points up through that. But Perl works on code
1336 points up to the maximum permissible unsigned number available on the
1337 platform. However, Perl will not accept these from input streams
1338 unless lax rules are being used, and will warn (using the warning
1339 category "non_unicode", which is a sub-category of "utf8") if any are
1340 output.
1341
1342 Since Unicode rules are not defined on these code points, if a Unicode-
1343 defined operation is done on them, Perl uses what we believe are
1344 sensible rules, while generally warning, using the "non_unicode"
1345 category. For example, "uc("\x{11_0000}")" will generate such a
1346 warning, returning the input parameter as its result, since Perl
1347 defines the uppercase of every non-Unicode code point to be the code
1348 point itself. (All the case changing operations, not just uppercasing,
1349 work this way.)
1350
1351 The situation with matching Unicode properties in regular expressions,
1352 the "\p{}" and "\P{}" constructs, against these code points is not as
1353 clear cut, and how these are handled has changed as we've gained
1354 experience.
1355
1356 One possibility is to treat any match against these code points as
1357 undefined. But since Perl doesn't have the concept of a match being
1358 undefined, it converts this to failing or "FALSE". This is almost, but
1359 not quite, what Perl did from v5.14 (when use of these code points
1360 became generally reliable) through v5.18. The difference is that Perl
1361 treated all "\p{}" matches as failing, but all "\P{}" matches as
1362 succeeding.
1363
1364 One problem with this is that it leads to unexpected, and confusing
1365 results in some cases:
1366
1367 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Failed on <= v5.18
1368 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Failed! on <= v5.18
1369
1370 That is, it treated both matches as undefined, and converted that to
1371 false (raising a warning on each). The first case is the expected
1372 result, but the second is likely counterintuitive: "How could both be
1373 false when they are complements?" Another problem was that the
1374 implementation optimized many Unicode property matches down to already
1375 existing simpler, faster operations, which don't raise the warning. We
1376 chose to not forgo those optimizations, which help the vast majority of
1377 matches, just to generate a warning for the unlikely event that an
1378 above-Unicode code point is being matched against.
1379
1380 As a result of these problems, starting in v5.20, what Perl does is to
1381 treat non-Unicode code points as just typical unassigned Unicode
1382 characters, and matches accordingly. (Note: Unicode has atypical
1383 unassigned code points. For example, it has noncharacter code points,
1384 and ones that, when they do get assigned, are destined to be written
1385 Right-to-left, as Arabic and Hebrew are. Perl assumes that no non-
1386 Unicode code point has any atypical properties.)
1387
1388 Perl, in most cases, will raise a warning when matching an above-
1389 Unicode code point against a Unicode property when the result is "TRUE"
1390 for "\p{}", and "FALSE" for "\P{}". For example:
1391
1392 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails, no warning
1393 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Succeeds, with warning
1394
1395 In both these examples, the character being matched is non-Unicode, so
1396 Unicode doesn't define how it should match. It clearly isn't an ASCII
1397 hex digit, so the first example clearly should fail, and so it does,
1398 with no warning. But it is arguable that the second example should
1399 have an undefined, hence "FALSE", result. So a warning is raised for
1400 it.
1401
1402 Thus the warning is raised for many fewer cases than in earlier Perls,
1403 and only when what the result is could be arguable. It turns out that
1404 none of the optimizations made by Perl (or are ever likely to be made)
1405 cause the warning to be skipped, so it solves both problems of Perl's
1406 earlier approach. The most commonly used property that is affected by
1407 this change is "\p{Unassigned}" which is a short form for
1408 "\p{General_Category=Unassigned}". Starting in v5.20, all non-Unicode
1409 code points are considered "Unassigned". In earlier releases the
1410 matches failed because the result was considered undefined.
1411
1412 The only place where the warning is not raised when it might ought to
1413 have been is if optimizations cause the whole pattern match to not even
1414 be attempted. For example, Perl may figure out that for a string to
1415 match a certain regular expression pattern, the string has to contain
1416 the substring "foobar". Before attempting the match, Perl may look for
1417 that substring, and if not found, immediately fail the match without
1418 actually trying it; so no warning gets generated even if the string
1419 contains an above-Unicode code point.
1420
1421 This behavior is more "Do what I mean" than in earlier Perls for most
1422 applications. But it catches fewer issues for code that needs to be
1423 strictly Unicode compliant. Therefore there is an additional mode of
1424 operation available to accommodate such code. This mode is enabled if
1425 a regular expression pattern is compiled within the lexical scope where
1426 the "non_unicode" warning class has been made fatal, say by:
1427
1428 use warnings FATAL => "non_unicode"
1429
1430 (see warnings). In this mode of operation, Perl will raise the warning
1431 for all matches against a non-Unicode code point (not just the arguable
1432 ones), and it skips the optimizations that might cause the warning to
1433 not be output. (It currently still won't warn if the match isn't even
1434 attempted, like in the "foobar" example above.)
1435
1436 In summary, Perl now normally treats non-Unicode code points as typical
1437 Unicode unassigned code points for regular expression matches, raising
1438 a warning only when it is arguable what the result should be. However,
1439 if this warning has been made fatal, it isn't skipped.
1440
1441 There is one exception to all this. "\p{All}" looks like a Unicode
1442 property, but it is a Perl extension that is defined to be true for all
1443 possible code points, Unicode or not, so no warning is ever generated
1444 when matching this against a non-Unicode code point. (Prior to v5.20,
1445 it was an exact synonym for "\p{Any}", matching code points 0 through
1446 0x10FFFF.)
1447
1448 Security Implications of Unicode
1449 First, read Unicode Security Considerations
1450 <http://www.unicode.org/reports/tr36>.
1451
1452 Also, note the following:
1453
1454 · Malformed UTF-8
1455
1456 UTF-8 is very structured, so many combinations of bytes are
1457 invalid. In the past, Perl tried to soldier on and make some sense
1458 of invalid combinations, but this can lead to security holes, so
1459 now, if the Perl core needs to process an invalid combination, it
1460 will either raise a fatal error, or will replace those bytes by the
1461 sequence that forms the Unicode REPLACEMENT CHARACTER, for which
1462 purpose Unicode created it.
1463
1464 Every code point can be represented by more than one possible
1465 syntactically valid UTF-8 sequence. Early on, both Unicode and
1466 Perl considered any of these to be valid, but now, all sequences
1467 longer than the shortest possible one are considered to be
1468 malformed.
1469
1470 Unicode considers many code points to be illegal, or to be avoided.
1471 Perl generally accepts them, once they have passed through any
1472 input filters that may try to exclude them. These have been
1473 discussed above (see "Surrogates" under UTF-16 in "Unicode
1474 Encodings", "Noncharacter code points", and "Beyond Unicode code
1475 points").
1476
1477 · Regular expression pattern matching may surprise you if you're not
1478 accustomed to Unicode. Starting in Perl 5.14, several pattern
1479 modifiers are available to control this, called the character set
1480 modifiers. Details are given in "Character set modifiers" in
1481 perlre.
1482
1483 As discussed elsewhere, Perl has one foot (two hooves?) planted in each
1484 of two worlds: the old world of ASCII and single-byte locales, and the
1485 new world of Unicode, upgrading when necessary. If your legacy code
1486 does not explicitly use Unicode, no automatic switch-over to Unicode
1487 should happen.
1488
1489 Unicode in Perl on EBCDIC
1490 Unicode is supported on EBCDIC platforms. See perlebcdic.
1491
1492 Unless ASCII vs. EBCDIC issues are specifically being discussed,
1493 references to UTF-8 encoding in this document and elsewhere should be
1494 read as meaning UTF-EBCDIC on EBCDIC platforms. See "Unicode and UTF"
1495 in perlebcdic.
1496
1497 Because UTF-EBCDIC is so similar to UTF-8, the differences are mostly
1498 hidden from you; "use utf8" (and NOT something like "use utfebcdic")
1499 declares the the script is in the platform's "native" 8-bit encoding of
1500 Unicode. (Similarly for the ":utf8" layer.)
1501
1502 Locales
1503 See "Unicode and UTF-8" in perllocale
1504
1505 When Unicode Does Not Happen
1506 There are still many places where Unicode (in some encoding or another)
1507 could be given as arguments or received as results, or both in Perl,
1508 but it is not, in spite of Perl having extensive ways to input and
1509 output in Unicode, and a few other "entry points" like the @ARGV array
1510 (which can sometimes be interpreted as UTF-8).
1511
1512 The following are such interfaces. Also, see "The "Unicode Bug"". For
1513 all of these interfaces Perl currently (as of v5.16.0) simply assumes
1514 byte strings both as arguments and results, or UTF-8 strings if the
1515 (deprecated) "encoding" pragma has been used.
1516
1517 One reason that Perl does not attempt to resolve the role of Unicode in
1518 these situations is that the answers are highly dependent on the
1519 operating system and the file system(s). For example, whether
1520 filenames can be in Unicode and in exactly what kind of encoding, is
1521 not exactly a portable concept. Similarly for "qx" and "system": how
1522 well will the "command-line interface" (and which of them?) handle
1523 Unicode?
1524
1525 · "chdir", "chmod", "chown", "chroot", "exec", "link", "lstat",
1526 "mkdir", "rename", "rmdir", "stat", "symlink", "truncate",
1527 "unlink", "utime", "-X"
1528
1529 · %ENV
1530
1531 · "glob" (aka the "<*>")
1532
1533 · "open", "opendir", "sysopen"
1534
1535 · "qx" (aka the backtick operator), "system"
1536
1537 · "readdir", "readlink"
1538
1539 The "Unicode Bug"
1540 The term, "Unicode bug" has been applied to an inconsistency with the
1541 code points in the "Latin-1 Supplement" block, that is, between 128 and
1542 255. Without a locale specified, unlike all other characters or code
1543 points, these characters can have very different semantics depending on
1544 the rules in effect. (Characters whose code points are above 255 force
1545 Unicode rules; whereas the rules for ASCII characters are the same
1546 under both ASCII and Unicode rules.)
1547
1548 Under Unicode rules, these upper-Latin1 characters are interpreted as
1549 Unicode code points, which means they have the same semantics as
1550 Latin-1 (ISO-8859-1) and C1 controls.
1551
1552 As explained in "ASCII Rules versus Unicode Rules", under ASCII rules,
1553 they are considered to be unassigned characters.
1554
1555 This can lead to unexpected results. For example, a string's semantics
1556 can suddenly change if a code point above 255 is appended to it, which
1557 changes the rules from ASCII to Unicode. As an example, consider the
1558 following program and its output:
1559
1560 $ perl -le'
1561 no feature "unicode_strings";
1562 $s1 = "\xC2";
1563 $s2 = "\x{2660}";
1564 for ($s1, $s2, $s1.$s2) {
1565 print /\w/ || 0;
1566 }
1567 '
1568 0
1569 0
1570 1
1571
1572 If there's no "\w" in "s1" nor in "s2", why does their concatenation
1573 have one?
1574
1575 This anomaly stems from Perl's attempt to not disturb older programs
1576 that didn't use Unicode, along with Perl's desire to add Unicode
1577 support seamlessly. But the result turned out to not be seamless. (By
1578 the way, you can choose to be warned when things like this happen. See
1579 "encoding::warnings".)
1580
1581 "use feature 'unicode_strings'" was added, starting in Perl v5.12, to
1582 address this problem. It affects these things:
1583
1584 · Changing the case of a scalar, that is, using "uc()", "ucfirst()",
1585 "lc()", and "lcfirst()", or "\L", "\U", "\u" and "\l" in double-
1586 quotish contexts, such as regular expression substitutions.
1587
1588 Under "unicode_strings" starting in Perl 5.12.0, Unicode rules are
1589 generally used. See "lc" in perlfunc for details on how this works
1590 in combination with various other pragmas.
1591
1592 · Using caseless ("/i") regular expression matching.
1593
1594 Starting in Perl 5.14.0, regular expressions compiled within the
1595 scope of "unicode_strings" use Unicode rules even when executed or
1596 compiled into larger regular expressions outside the scope.
1597
1598 · Matching any of several properties in regular expressions.
1599
1600 These properties are "\b" (without braces), "\B" (without braces),
1601 "\s", "\S", "\w", "\W", and all the Posix character classes except
1602 "[[:ascii:]]".
1603
1604 Starting in Perl 5.14.0, regular expressions compiled within the
1605 scope of "unicode_strings" use Unicode rules even when executed or
1606 compiled into larger regular expressions outside the scope.
1607
1608 · In "quotemeta" or its inline equivalent "\Q".
1609
1610 Starting in Perl 5.16.0, consistent quoting rules are used within
1611 the scope of "unicode_strings", as described in "quotemeta" in
1612 perlfunc. Prior to that, or outside its scope, no code points
1613 above 127 are quoted in UTF-8 encoded strings, but in byte encoded
1614 strings, code points between 128-255 are always quoted.
1615
1616 · In the ".." or range operator.
1617
1618 Starting in Perl 5.26.0, the range operator on strings treats their
1619 lengths consistently within the scope of "unicode_strings". Prior
1620 to that, or outside its scope, it could produce strings whose
1621 length in characters exceeded that of the right-hand side, where
1622 the right-hand side took up more bytes than the correct range
1623 endpoint.
1624
1625 · In "split"'s special-case whitespace splitting.
1626
1627 Starting in Perl 5.28.0, the "split" function with a pattern
1628 specified as a string containing a single space handles whitespace
1629 characters consistently within the scope of of "unicode_strings".
1630 Prior to that, or outside its scope, characters that are whitespace
1631 according to Unicode rules but not according to ASCII rules were
1632 treated as field contents rather than field separators when they
1633 appear in byte-encoded strings.
1634
1635 You can see from the above that the effect of "unicode_strings"
1636 increased over several Perl releases. (And Perl's support for Unicode
1637 continues to improve; it's best to use the latest available release in
1638 order to get the most complete and accurate results possible.) Note
1639 that "unicode_strings" is automatically chosen if you "use 5.012" or
1640 higher.
1641
1642 For Perls earlier than those described above, or when a string is
1643 passed to a function outside the scope of "unicode_strings", see the
1644 next section.
1645
1646 Forcing Unicode in Perl (Or Unforcing Unicode in Perl)
1647 Sometimes (see "When Unicode Does Not Happen" or "The "Unicode Bug"")
1648 there are situations where you simply need to force a byte string into
1649 UTF-8, or vice versa. The standard module Encode can be used for this,
1650 or the low-level calls "utf8::upgrade($bytestring)" and
1651 "utf8::downgrade($utf8string[, FAIL_OK])".
1652
1653 Note that "utf8::downgrade()" can fail if the string contains
1654 characters that don't fit into a byte.
1655
1656 Calling either function on a string that already is in the desired
1657 state is a no-op.
1658
1659 "ASCII Rules versus Unicode Rules" gives all the ways that a string is
1660 made to use Unicode rules.
1661
1662 Using Unicode in XS
1663 See "Unicode Support" in perlguts for an introduction to Unicode at the
1664 XS level, and "Unicode Support" in perlapi for the API details.
1665
1666 Hacking Perl to work on earlier Unicode versions (for very serious hackers
1667 only)
1668 Perl by default comes with the latest supported Unicode version built-
1669 in, but the goal is to allow you to change to use any earlier one. In
1670 Perls v5.20 and v5.22, however, the earliest usable version is Unicode
1671 5.1. Perl v5.18 and v5.24 are able to handle all earlier versions.
1672
1673 Download the files in the desired version of Unicode from the Unicode
1674 web site <http://www.unicode.org>). These should replace the existing
1675 files in lib/unicore in the Perl source tree. Follow the instructions
1676 in README.perl in that directory to change some of their names, and
1677 then build perl (see INSTALL).
1678
1679 Porting code from perl-5.6.X
1680 Perls starting in 5.8 have a different Unicode model from 5.6. In 5.6
1681 the programmer was required to use the "utf8" pragma to declare that a
1682 given scope expected to deal with Unicode data and had to make sure
1683 that only Unicode data were reaching that scope. If you have code that
1684 is working with 5.6, you will need some of the following adjustments to
1685 your code. The examples are written such that the code will continue to
1686 work under 5.6, so you should be safe to try them out.
1687
1688 · A filehandle that should read or write UTF-8
1689
1690 if ($] > 5.008) {
1691 binmode $fh, ":encoding(UTF-8)";
1692 }
1693
1694 · A scalar that is going to be passed to some extension
1695
1696 Be it "Compress::Zlib", "Apache::Request" or any extension that has
1697 no mention of Unicode in the manpage, you need to make sure that the
1698 UTF8 flag is stripped off. Note that at the time of this writing
1699 (January 2012) the mentioned modules are not UTF-8-aware. Please
1700 check the documentation to verify if this is still true.
1701
1702 if ($] > 5.008) {
1703 require Encode;
1704 $val = Encode::encode("UTF-8", $val); # make octets
1705 }
1706
1707 · A scalar we got back from an extension
1708
1709 If you believe the scalar comes back as UTF-8, you will most likely
1710 want the UTF8 flag restored:
1711
1712 if ($] > 5.008) {
1713 require Encode;
1714 $val = Encode::decode("UTF-8", $val);
1715 }
1716
1717 · Same thing, if you are really sure it is UTF-8
1718
1719 if ($] > 5.008) {
1720 require Encode;
1721 Encode::_utf8_on($val);
1722 }
1723
1724 · A wrapper for DBI "fetchrow_array" and "fetchrow_hashref"
1725
1726 When the database contains only UTF-8, a wrapper function or method
1727 is a convenient way to replace all your "fetchrow_array" and
1728 "fetchrow_hashref" calls. A wrapper function will also make it
1729 easier to adapt to future enhancements in your database driver. Note
1730 that at the time of this writing (January 2012), the DBI has no
1731 standardized way to deal with UTF-8 data. Please check the DBI
1732 documentation to verify if that is still true.
1733
1734 sub fetchrow {
1735 # $what is one of fetchrow_{array,hashref}
1736 my($self, $sth, $what) = @_;
1737 if ($] < 5.008) {
1738 return $sth->$what;
1739 } else {
1740 require Encode;
1741 if (wantarray) {
1742 my @arr = $sth->$what;
1743 for (@arr) {
1744 defined && /[^\000-\177]/ && Encode::_utf8_on($_);
1745 }
1746 return @arr;
1747 } else {
1748 my $ret = $sth->$what;
1749 if (ref $ret) {
1750 for my $k (keys %$ret) {
1751 defined
1752 && /[^\000-\177]/
1753 && Encode::_utf8_on($_) for $ret->{$k};
1754 }
1755 return $ret;
1756 } else {
1757 defined && /[^\000-\177]/ && Encode::_utf8_on($_) for $ret;
1758 return $ret;
1759 }
1760 }
1761 }
1762 }
1763
1764 · A large scalar that you know can only contain ASCII
1765
1766 Scalars that contain only ASCII and are marked as UTF-8 are
1767 sometimes a drag to your program. If you recognize such a situation,
1768 just remove the UTF8 flag:
1769
1770 utf8::downgrade($val) if $] > 5.008;
1771
1773 See also "The "Unicode Bug"" above.
1774
1775 Interaction with Extensions
1776 When Perl exchanges data with an extension, the extension should be
1777 able to understand the UTF8 flag and act accordingly. If the extension
1778 doesn't recognize that flag, it's likely that the extension will return
1779 incorrectly-flagged data.
1780
1781 So if you're working with Unicode data, consult the documentation of
1782 every module you're using if there are any issues with Unicode data
1783 exchange. If the documentation does not talk about Unicode at all,
1784 suspect the worst and probably look at the source to learn how the
1785 module is implemented. Modules written completely in Perl shouldn't
1786 cause problems. Modules that directly or indirectly access code written
1787 in other programming languages are at risk.
1788
1789 For affected functions, the simple strategy to avoid data corruption is
1790 to always make the encoding of the exchanged data explicit. Choose an
1791 encoding that you know the extension can handle. Convert arguments
1792 passed to the extensions to that encoding and convert results back from
1793 that encoding. Write wrapper functions that do the conversions for you,
1794 so you can later change the functions when the extension catches up.
1795
1796 To provide an example, let's say the popular "Foo::Bar::escape_html"
1797 function doesn't deal with Unicode data yet. The wrapper function would
1798 convert the argument to raw UTF-8 and convert the result back to Perl's
1799 internal representation like so:
1800
1801 sub my_escape_html ($) {
1802 my($what) = shift;
1803 return unless defined $what;
1804 Encode::decode("UTF-8", Foo::Bar::escape_html(
1805 Encode::encode("UTF-8", $what)));
1806 }
1807
1808 Sometimes, when the extension does not convert data but just stores and
1809 retrieves it, you will be able to use the otherwise dangerous
1810 "Encode::_utf8_on()" function. Let's say the popular "Foo::Bar"
1811 extension, written in C, provides a "param" method that lets you store
1812 and retrieve data according to these prototypes:
1813
1814 $self->param($name, $value); # set a scalar
1815 $value = $self->param($name); # retrieve a scalar
1816
1817 If it does not yet provide support for any encoding, one could write a
1818 derived class with such a "param" method:
1819
1820 sub param {
1821 my($self,$name,$value) = @_;
1822 utf8::upgrade($name); # make sure it is UTF-8 encoded
1823 if (defined $value) {
1824 utf8::upgrade($value); # make sure it is UTF-8 encoded
1825 return $self->SUPER::param($name,$value);
1826 } else {
1827 my $ret = $self->SUPER::param($name);
1828 Encode::_utf8_on($ret); # we know, it is UTF-8 encoded
1829 return $ret;
1830 }
1831 }
1832
1833 Some extensions provide filters on data entry/exit points, such as
1834 "DB_File::filter_store_key" and family. Look out for such filters in
1835 the documentation of your extensions; they can make the transition to
1836 Unicode data much easier.
1837
1838 Speed
1839 Some functions are slower when working on UTF-8 encoded strings than on
1840 byte encoded strings. All functions that need to hop over characters
1841 such as "length()", "substr()" or "index()", or matching regular
1842 expressions can work much faster when the underlying data are byte-
1843 encoded.
1844
1845 In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1 a
1846 caching scheme was introduced which improved the situation. In
1847 general, operations with UTF-8 encoded strings are still slower. As an
1848 example, the Unicode properties (character classes) like "\p{Nd}" are
1849 known to be quite a bit slower (5-20 times) than their simpler
1850 counterparts like "[0-9]" (then again, there are hundreds of Unicode
1851 characters matching "Nd" compared with the 10 ASCII characters matching
1852 "[0-9]").
1853
1855 perlunitut, perluniintro, perluniprops, Encode, open, utf8, bytes,
1856 perlretut, "${^UNICODE}" in perlvar,
1857 <http://www.unicode.org/reports/tr44>).
1858
1859
1860
1861perl v5.26.3 2019-05-11 PERLUNICODE(1)