Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlunicode.html
blob69165fa50f064d87d9c56733a1479843a4215112
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perlunicode - Unicode support in Perl</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perlunicode - Unicode support in Perl</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <ul>
26 <li><a href="#important_caveats">Important Caveats</a></li>
27 <li><a href="#byte_and_character_semantics">Byte and Character Semantics</a></li>
28 <li><a href="#effects_of_character_semantics">Effects of Character Semantics</a></li>
29 <li><a href="#scripts">Scripts</a></li>
30 <li><a href="#blocks">Blocks</a></li>
31 <li><a href="#userdefined_character_properties">User-Defined Character Properties</a></li>
32 <li><a href="#character_encodings_for_input_and_output">Character Encodings for Input and Output</a></li>
33 <li><a href="#unicode_regular_expression_support_level">Unicode Regular Expression Support Level</a></li>
34 <li><a href="#unicode_encodings">Unicode Encodings</a></li>
35 <li><a href="#security_implications_of_unicode">Security Implications of Unicode</a></li>
36 <li><a href="#unicode_in_perl_on_ebcdic">Unicode in Perl on EBCDIC</a></li>
37 <li><a href="#locales">Locales</a></li>
38 <li><a href="#when_unicode_does_not_happen">When Unicode Does Not Happen</a></li>
39 <li><a href="#forcing_unicode_in_perl__or_unforcing_unicode_in_perl_">Forcing Unicode in Perl (Or Unforcing Unicode in Perl)</a></li>
40 <li><a href="#using_unicode_in_xs">Using Unicode in XS</a></li>
41 </ul>
43 <li><a href="#bugs">BUGS</a></li>
44 <ul>
46 <li><a href="#interaction_with_locales">Interaction with Locales</a></li>
47 <li><a href="#interaction_with_extensions">Interaction with Extensions</a></li>
48 <li><a href="#speed">Speed</a></li>
49 <li><a href="#porting_code_from_perl5_6_x">Porting code from perl-5.6.X</a></li>
50 </ul>
52 <li><a href="#see_also">SEE ALSO</a></li>
53 </ul>
54 <!-- INDEX END -->
56 <hr />
57 <p>
58 </p>
59 <h1><a name="name">NAME</a></h1>
60 <p>perlunicode - Unicode support in Perl</p>
61 <p>
62 </p>
63 <hr />
64 <h1><a name="description">DESCRIPTION</a></h1>
65 <p>
66 </p>
67 <h2><a name="important_caveats">Important Caveats</a></h2>
68 <p>Unicode support is an extensive requirement. While Perl does not
69 implement the Unicode standard or the accompanying technical reports
70 from cover to cover, Perl does support many Unicode features.</p>
71 <dl>
72 <dt><strong><a name="item_input_and_output_layers">Input and Output Layers</a></strong>
74 <dd>
75 <p>Perl knows when a filehandle uses Perl's internal Unicode encodings
76 (UTF-8, or UTF-EBCDIC if in EBCDIC) if the filehandle is opened with
77 the ``:utf8'' layer. Other encodings can be converted to Perl's
78 encoding on input or from Perl's encoding on output by use of the
79 ``:encoding(...)'' layer. See <a href="file://C|\msysgit\mingw\html/lib/open.html">the open manpage</a>.</p>
80 </dd>
81 <dd>
82 <p>To indicate that Perl source itself is using a particular encoding,
83 see <a href="file://C|\msysgit\mingw\html/lib/encoding.html">the encoding manpage</a>.</p>
84 </dd>
85 </li>
86 <dt><strong><a name="item_regular_expressions">Regular Expressions</a></strong>
88 <dd>
89 <p>The regular expression compiler produces polymorphic opcodes. That is,
90 the pattern adapts to the data and automatically switches to the Unicode
91 character scheme when presented with Unicode data--or instead uses
92 a traditional byte scheme when presented with byte data.</p>
93 </dd>
94 </li>
95 <dt><strong><a name="item_use_utf8_still_needed_to_enable_utf_2d8_2futf_2deb"><code>use utf8</code> still needed to enable UTF-8/UTF-EBCDIC in scripts</a></strong>
97 <dd>
98 <p>As a compatibility measure, the <code>use utf8</code> pragma must be explicitly
99 included to enable recognition of UTF-8 in the Perl scripts themselves
100 (in string or regular expression literals, or in identifier names) on
101 ASCII-based machines or to recognize UTF-EBCDIC on EBCDIC-based
102 machines. <strong>These are the only times when an explicit <code>use utf8</code>
103 is needed.</strong> See <a href="file://C|\msysgit\mingw\html/lib/utf8.html">the utf8 manpage</a>.</p>
104 </dd>
105 <dd>
106 <p>You can also use the <code>encoding</code> pragma to change the default encoding
107 of the data in your script; see <a href="file://C|\msysgit\mingw\html/lib/encoding.html">the encoding manpage</a>.</p>
108 </dd>
109 </li>
110 <dt><strong><a name="item_bom_2dmarked_scripts_and_utf_2d16_scripts_autodete">BOM-marked scripts and UTF-16 scripts autodetected</a></strong>
112 <dd>
113 <p>If a Perl script begins marked with the Unicode BOM (UTF-16LE, UTF16-BE,
114 or UTF-8), or if the script looks like non-BOM-marked UTF-16 of either
115 endianness, Perl will correctly read in the script as Unicode.
116 (BOMless UTF-8 cannot be effectively recognized or differentiated from
117 ISO 8859-1 or other eight-bit encodings.)</p>
118 </dd>
119 </li>
120 <dt><strong><a name="item_use_encoding_needed_to_upgrade_non_2dlatin_2d1_byt"><code>use encoding</code> needed to upgrade non-Latin-1 byte strings</a></strong>
122 <dd>
123 <p>By default, there is a fundamental asymmetry in Perl's unicode model:
124 implicit upgrading from byte strings to Unicode strings assumes that
125 they were encoded in <em>ISO 8859-1 (Latin-1)</em>, but Unicode strings are
126 downgraded with UTF-8 encoding. This happens because the first 256
127 codepoints in Unicode happens to agree with Latin-1.</p>
128 </dd>
129 <dd>
130 <p>If you wish to interpret byte strings as UTF-8 instead, use the
131 <code>encoding</code> pragma:</p>
132 </dd>
133 <dd>
134 <pre>
135 use encoding 'utf8';</pre>
136 </dd>
137 <dd>
138 <p>See <a href="#byte_and_character_semantics">Byte and Character Semantics</a> for more details.</p>
139 </dd>
140 </li>
141 </dl>
143 </p>
144 <h2><a name="byte_and_character_semantics">Byte and Character Semantics</a></h2>
145 <p>Beginning with version 5.6, Perl uses logically-wide characters to
146 represent strings internally.</p>
147 <p>In future, Perl-level operations will be expected to work with
148 characters rather than bytes.</p>
149 <p>However, as an interim compatibility measure, Perl aims to
150 provide a safe migration path from byte semantics to character
151 semantics for programs. For operations where Perl can unambiguously
152 decide that the input data are characters, Perl switches to
153 character semantics. For operations where this determination cannot
154 be made without additional information from the user, Perl decides in
155 favor of compatibility and chooses to use byte semantics.</p>
156 <p>This behavior preserves compatibility with earlier versions of Perl,
157 which allowed byte semantics in Perl operations only if
158 none of the program's inputs were marked as being as source of Unicode
159 character data. Such data may come from filehandles, from calls to
160 external programs, from information provided by the system (such as %ENV),
161 or from literals and constants in the source text.</p>
162 <p>The <code>bytes</code> pragma will always, regardless of platform, force byte
163 semantics in a particular lexical scope. See <a href="file://C|\msysgit\mingw\html/lib/bytes.html">the bytes manpage</a>.</p>
164 <p>The <code>utf8</code> pragma is primarily a compatibility device that enables
165 recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
166 Note that this pragma is only required while Perl defaults to byte
167 semantics; when character semantics become the default, this pragma
168 may become a no-op. See <a href="file://C|\msysgit\mingw\html/lib/utf8.html">the utf8 manpage</a>.</p>
169 <p>Unless explicitly stated, Perl operators use character semantics
170 for Unicode data and byte semantics for non-Unicode data.
171 The decision to use character semantics is made transparently. If
172 input data comes from a Unicode source--for example, if a character
173 encoding layer is added to a filehandle or a literal Unicode
174 string constant appears in a program--character semantics apply.
175 Otherwise, byte semantics are in effect. The <code>bytes</code> pragma should
176 be used to force byte semantics on Unicode data.</p>
177 <p>If strings operating under byte semantics and strings with Unicode
178 character data are concatenated, the new string will be created by
179 decoding the byte strings as <em>ISO 8859-1 (Latin-1)</em>, even if the
180 old Unicode string used EBCDIC. This translation is done without
181 regard to the system's native 8-bit encoding. To change this for
182 systems with non-Latin-1 and non-EBCDIC native encodings, use the
183 <code>encoding</code> pragma. See <a href="file://C|\msysgit\mingw\html/lib/encoding.html">the encoding manpage</a>.</p>
184 <p>Under character semantics, many operations that formerly operated on
185 bytes now operate on characters. A character in Perl is
186 logically just a number ranging from 0 to 2**31 or so. Larger
187 characters may encode into longer sequences of bytes internally, but
188 this internal detail is mostly hidden for Perl code.
189 See <a href="file://C|\msysgit\mingw\html/pod/perluniintro.html">the perluniintro manpage</a> for more.</p>
191 </p>
192 <h2><a name="effects_of_character_semantics">Effects of Character Semantics</a></h2>
193 <p>Character semantics have the following effects:</p>
194 <ul>
195 <li>
196 <p>Strings--including hash keys--and regular expression patterns may
197 contain characters that have an ordinal value larger than 255.</p>
198 <p>If you use a Unicode editor to edit your program, Unicode characters
199 may occur directly within the literal strings in one of the various
200 Unicode encodings (UTF-8, UTF-EBCDIC, UCS-2, etc.), but will be recognized
201 as such and converted to Perl's internal representation only if the
202 appropriate <a href="file://C|\msysgit\mingw\html/lib/encoding.html">the encoding manpage</a> is specified.</p>
203 <p>Unicode characters can also be added to a string by using the
204 <code>\x{...}</code> notation. The Unicode code for the desired character, in
205 hexadecimal, should be placed in the braces. For instance, a smiley
206 face is <code>\x{263A}</code>. This encoding scheme only works for characters
207 with a code of 0x100 or above.</p>
208 <p>Additionally, if you</p>
209 <pre>
210 use charnames ':full';</pre>
211 <p>you can use the <code>\N{...}</code> notation and put the official Unicode
212 character name within the braces, such as <code>\N{WHITE SMILING FACE}</code>.</p>
213 </li>
214 <li>
215 <p>If an appropriate <a href="file://C|\msysgit\mingw\html/lib/encoding.html">the encoding manpage</a> is specified, identifiers within the
216 Perl script may contain Unicode alphanumeric characters, including
217 ideographs. Perl does not currently attempt to canonicalize variable
218 names.</p>
219 </li>
220 <li>
221 <p>Regular expressions match characters instead of bytes. ``.'' matches
222 a character instead of a byte. The <code>\C</code> pattern is provided to force
223 a match a single byte--a <code>char</code> in C, hence <code>\C</code>.</p>
224 </li>
225 <li>
226 <p>Character classes in regular expressions match characters instead of
227 bytes and match against the character properties specified in the
228 Unicode properties database. <code>\w</code> can be used to match a Japanese
229 ideograph, for instance.</p>
230 <p>(However, and as a limitation of the current implementation, using
231 <code>\w</code> or <code>\W</code> <em>inside</em> a <code>[...]</code> character class will still match
232 with byte semantics.)</p>
233 </li>
234 <li>
235 <p>Named Unicode properties, scripts, and block ranges may be used like
236 character classes via the <code>\p{}</code> ``matches property'' construct and
237 the <code>\P{}</code> negation, ``doesn't match property''.</p>
238 <p>For instance, <code>\p{Lu}</code> matches any character with the Unicode ``Lu''
239 (Letter, uppercase) property, while <code>\p{M}</code> matches any character
240 with an ``M'' (mark--accents and such) property. Brackets are not
241 required for single letter properties, so <code>\p{M}</code> is equivalent to
242 <code>\pM</code>. Many predefined properties are available, such as
243 <code>\p{Mirrored}</code> and <code>\p{Tibetan}</code>.</p>
244 <p>The official Unicode script and block names have spaces and dashes as
245 separators, but for convenience you can use dashes, spaces, or
246 underbars, and case is unimportant. It is recommended, however, that
247 for consistency you use the following naming: the official Unicode
248 script, property, or block name (see below for the additional rules
249 that apply to block names) with whitespace and dashes removed, and the
250 words ``uppercase-first-lowercase-rest''. <code>Latin-1 Supplement</code> thus
251 becomes <code>Latin1Supplement</code>.</p>
252 <p>You can also use negation in both <code>\p{}</code> and <code>\P{}</code> by introducing a caret
253 (^) between the first brace and the property name: <code>\p{^Tamil}</code> is
254 equal to <code>\P{Tamil}</code>.</p>
255 <p><strong>NOTE: the properties, scripts, and blocks listed here are as of
256 Unicode 3.2.0, March 2002, or Perl 5.8.0, July 2002. Unicode 4.0.0
257 came out in April 2003, and Perl 5.8.1 in September 2003.</strong></p>
258 <p>Here are the basic Unicode General Category properties, followed by their
259 long form. You can use either; <code>\p{Lu}</code> and <code>\p{UppercaseLetter}</code>,
260 for instance, are identical.</p>
261 <pre>
262 Short Long</pre>
263 <pre>
264 L Letter
265 LC CasedLetter
266 Lu UppercaseLetter
267 Ll LowercaseLetter
268 Lt TitlecaseLetter
269 Lm ModifierLetter
270 Lo OtherLetter</pre>
271 <pre>
272 M Mark
273 Mn NonspacingMark
274 Mc SpacingMark
275 Me EnclosingMark</pre>
276 <pre>
277 N Number
278 Nd DecimalNumber
279 Nl LetterNumber
280 No OtherNumber</pre>
281 <pre>
282 P Punctuation
283 Pc ConnectorPunctuation
284 Pd DashPunctuation
285 Ps OpenPunctuation
286 Pe ClosePunctuation
287 Pi InitialPunctuation
288 (may behave like Ps or Pe depending on usage)
289 Pf FinalPunctuation
290 (may behave like Ps or Pe depending on usage)
291 Po OtherPunctuation</pre>
292 <pre>
293 S Symbol
294 Sm MathSymbol
295 Sc CurrencySymbol
296 Sk ModifierSymbol
297 So OtherSymbol</pre>
298 <pre>
299 Z Separator
300 Zs SpaceSeparator
301 Zl LineSeparator
302 Zp ParagraphSeparator</pre>
303 <pre>
304 C Other
305 Cc Control
306 Cf Format
307 Cs Surrogate (not usable)
308 Co PrivateUse
309 Cn Unassigned</pre>
310 <p>Single-letter properties match all characters in any of the
311 two-letter sub-properties starting with the same letter.
312 <code>LC</code> and <code>L&amp;</code> are special cases, which are aliases for the set of
313 <code>Ll</code>, <code>Lu</code>, and <code>Lt</code>.</p>
314 <p>Because Perl hides the need for the user to understand the internal
315 representation of Unicode characters, there is no need to implement
316 the somewhat messy concept of surrogates. <code>Cs</code> is therefore not
317 supported.</p>
318 <p>Because scripts differ in their directionality--Hebrew is
319 written right to left, for example--Unicode supplies these properties in
320 the BidiClass class:</p>
321 <pre>
322 Property Meaning</pre>
323 <pre>
324 L Left-to-Right
325 LRE Left-to-Right Embedding
326 LRO Left-to-Right Override
327 R Right-to-Left
328 AL Right-to-Left Arabic
329 RLE Right-to-Left Embedding
330 RLO Right-to-Left Override
331 PDF Pop Directional Format
332 EN European Number
333 ES European Number Separator
334 ET European Number Terminator
335 AN Arabic Number
336 CS Common Number Separator
337 NSM Non-Spacing Mark
338 BN Boundary Neutral
339 B Paragraph Separator
340 S Segment Separator
341 WS Whitespace
342 ON Other Neutrals</pre>
343 <p>For example, <code>\p{BidiClass:R}</code> matches characters that are normally
344 written right to left.</p>
345 </li>
346 </ul>
348 </p>
349 <h2><a name="scripts">Scripts</a></h2>
350 <p>The script names which can be used by <code>\p{...}</code> and <code>\P{...}</code>,
351 such as in <code>\p{Latin}</code> or <code>\p{Cyrillic}</code>, are as follows:</p>
352 <pre>
353 Arabic
354 Armenian
355 Bengali
356 Bopomofo
357 Buhid
358 CanadianAboriginal
359 Cherokee
360 Cyrillic
361 Deseret
362 Devanagari
363 Ethiopic
364 Georgian
365 Gothic
366 Greek
367 Gujarati
368 Gurmukhi
370 Hangul
371 Hanunoo
372 Hebrew
373 Hiragana
374 Inherited
375 Kannada
376 Katakana
377 Khmer
379 Latin
380 Malayalam
381 Mongolian
382 Myanmar
383 Ogham
384 OldItalic
385 Oriya
386 Runic
387 Sinhala
388 Syriac
389 Tagalog
390 Tagbanwa
391 Tamil
392 Telugu
393 Thaana
394 Thai
395 Tibetan
396 Yi</pre>
397 <p>Extended property classes can supplement the basic
398 properties, defined by the <em>PropList</em> Unicode database:</p>
399 <pre>
400 ASCIIHexDigit
401 BidiControl
402 Dash
403 Deprecated
404 Diacritic
405 Extender
406 GraphemeLink
407 HexDigit
408 Hyphen
409 Ideographic
410 IDSBinaryOperator
411 IDSTrinaryOperator
412 JoinControl
413 LogicalOrderException
414 NoncharacterCodePoint
415 OtherAlphabetic
416 OtherDefaultIgnorableCodePoint
417 OtherGraphemeExtend
418 OtherLowercase
419 OtherMath
420 OtherUppercase
421 QuotationMark
422 Radical
423 SoftDotted
424 TerminalPunctuation
425 UnifiedIdeograph
426 WhiteSpace</pre>
427 <p>and there are further derived properties:</p>
428 <pre>
429 Alphabetic Lu + Ll + Lt + Lm + Lo + OtherAlphabetic
430 Lowercase Ll + OtherLowercase
431 Uppercase Lu + OtherUppercase
432 Math Sm + OtherMath</pre>
433 <pre>
434 ID_Start Lu + Ll + Lt + Lm + Lo + Nl
435 ID_Continue ID_Start + Mn + Mc + Nd + Pc</pre>
436 <pre>
437 Any Any character
438 Assigned Any non-Cn character (i.e. synonym for \P{Cn})
439 Unassigned Synonym for \p{Cn}
440 Common Any character (or unassigned code point)
441 not explicitly assigned to a script</pre>
442 <p>For backward compatibility (with Perl 5.6), all properties mentioned
443 so far may have <code>Is</code> prepended to their name, so <code>\P{IsLu}</code>, for
444 example, is equal to <code>\P{Lu}</code>.</p>
446 </p>
447 <h2><a name="blocks">Blocks</a></h2>
448 <p>In addition to <strong>scripts</strong>, Unicode also defines <strong>blocks</strong> of
449 characters. The difference between scripts and blocks is that the
450 concept of scripts is closer to natural languages, while the concept
451 of blocks is more of an artificial grouping based on groups of 256
452 Unicode characters. For example, the <code>Latin</code> script contains letters
453 from many blocks but does not contain all the characters from those
454 blocks. It does not, for example, contain digits, because digits are
455 shared across many scripts. Digits and similar groups, like
456 punctuation, are in a category called <code>Common</code>.</p>
457 <p>For more about scripts, see the UTR #24:</p>
458 <pre>
459 <a href="http://www.unicode.org/unicode/reports/tr24/">http://www.unicode.org/unicode/reports/tr24/</a></pre>
460 <p>For more about blocks, see:</p>
461 <pre>
462 <a href="http://www.unicode.org/Public/UNIDATA/Blocks.txt">http://www.unicode.org/Public/UNIDATA/Blocks.txt</a></pre>
463 <p>Block names are given with the <code>In</code> prefix. For example, the
464 Katakana block is referenced via <code>\p{InKatakana}</code>. The <code>In</code>
465 prefix may be omitted if there is no naming conflict with a script
466 or any other property, but it is recommended that <code>In</code> always be used
467 for block tests to avoid confusion.</p>
468 <p>These block names are supported:</p>
469 <pre>
470 InAlphabeticPresentationForms
471 InArabic
472 InArabicPresentationFormsA
473 InArabicPresentationFormsB
474 InArmenian
475 InArrows
476 InBasicLatin
477 InBengali
478 InBlockElements
479 InBopomofo
480 InBopomofoExtended
481 InBoxDrawing
482 InBraillePatterns
483 InBuhid
484 InByzantineMusicalSymbols
485 InCJKCompatibility
486 InCJKCompatibilityForms
487 InCJKCompatibilityIdeographs
488 InCJKCompatibilityIdeographsSupplement
489 InCJKRadicalsSupplement
490 InCJKSymbolsAndPunctuation
491 InCJKUnifiedIdeographs
492 InCJKUnifiedIdeographsExtensionA
493 InCJKUnifiedIdeographsExtensionB
494 InCherokee
495 InCombiningDiacriticalMarks
496 InCombiningDiacriticalMarksforSymbols
497 InCombiningHalfMarks
498 InControlPictures
499 InCurrencySymbols
500 InCyrillic
501 InCyrillicSupplementary
502 InDeseret
503 InDevanagari
504 InDingbats
505 InEnclosedAlphanumerics
506 InEnclosedCJKLettersAndMonths
507 InEthiopic
508 InGeneralPunctuation
509 InGeometricShapes
510 InGeorgian
511 InGothic
512 InGreekExtended
513 InGreekAndCoptic
514 InGujarati
515 InGurmukhi
516 InHalfwidthAndFullwidthForms
517 InHangulCompatibilityJamo
518 InHangulJamo
519 InHangulSyllables
520 InHanunoo
521 InHebrew
522 InHighPrivateUseSurrogates
523 InHighSurrogates
524 InHiragana
525 InIPAExtensions
526 InIdeographicDescriptionCharacters
527 InKanbun
528 InKangxiRadicals
529 InKannada
530 InKatakana
531 InKatakanaPhoneticExtensions
532 InKhmer
533 InLao
534 InLatin1Supplement
535 InLatinExtendedA
536 InLatinExtendedAdditional
537 InLatinExtendedB
538 InLetterlikeSymbols
539 InLowSurrogates
540 InMalayalam
541 InMathematicalAlphanumericSymbols
542 InMathematicalOperators
543 InMiscellaneousMathematicalSymbolsA
544 InMiscellaneousMathematicalSymbolsB
545 InMiscellaneousSymbols
546 InMiscellaneousTechnical
547 InMongolian
548 InMusicalSymbols
549 InMyanmar
550 InNumberForms
551 InOgham
552 InOldItalic
553 InOpticalCharacterRecognition
554 InOriya
555 InPrivateUseArea
556 InRunic
557 InSinhala
558 InSmallFormVariants
559 InSpacingModifierLetters
560 InSpecials
561 InSuperscriptsAndSubscripts
562 InSupplementalArrowsA
563 InSupplementalArrowsB
564 InSupplementalMathematicalOperators
565 InSupplementaryPrivateUseAreaA
566 InSupplementaryPrivateUseAreaB
567 InSyriac
568 InTagalog
569 InTagbanwa
570 InTags
571 InTamil
572 InTelugu
573 InThaana
574 InThai
575 InTibetan
576 InUnifiedCanadianAboriginalSyllabics
577 InVariationSelectors
578 InYiRadicals
579 InYiSyllables</pre>
580 <ul>
581 <li>
582 <p>The special pattern <code>\X</code> matches any extended Unicode
583 sequence--``a combining character sequence'' in Standardese--where the
584 first character is a base character and subsequent characters are mark
585 characters that apply to the base character. <code>\X</code> is equivalent to
586 <code>(?:\PM\pM*)</code>.</p>
587 </li>
588 <li>
589 <p>The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_tr_"><code>tr///</code></a> operator translates characters instead of bytes. Note
590 that the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_tr_"><code>tr///CU</code></a> functionality has been removed. For similar
591 functionality see pack('U0', ...) and pack('C0', ...).</p>
592 </li>
593 <li>
594 <p>Case translation operators use the Unicode case translation tables
595 when character input is provided. Note that <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_uc"><code>uc()</code></a>, or <code>\U</code> in
596 interpolated strings, translates to uppercase, while <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ucfirst"><code>ucfirst</code></a>,
597 or <code>\u</code> in interpolated strings, translates to titlecase in languages
598 that make the distinction.</p>
599 </li>
600 <li>
601 <p>Most operators that deal with positions or lengths in a string will
602 automatically switch to using character positions, including
603 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_chop"><code>chop()</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_chomp"><code>chomp()</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item_substr"><code>substr()</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_index"><code>index()</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_rindex"><code>rindex()</code></a>,
604 <code>sprintf()</code>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_write"><code>write()</code></a>, and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_length"><code>length()</code></a>. Operators that
605 specifically do not switch include <code>vec()</code>, <code>pack()</code>, and
606 <code>unpack()</code>. Operators that really don't care include
607 operators that treats strings as a bucket of bits such as <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_sort"><code>sort()</code></a>,
608 and operators dealing with filenames.</p>
609 </li>
610 <li>
611 <p>The <code>pack()</code>/<code>unpack()</code> letters <code>c</code> and <code>C</code> do <em>not</em> change,
612 since they are often used for byte-oriented formats. Again, think
613 <code>char</code> in the C language.</p>
614 <p>There is a new <code>U</code> specifier that converts between Unicode characters
615 and code points.</p>
616 </li>
617 <li>
618 <p>The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_chr"><code>chr()</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ord"><code>ord()</code></a> functions work on characters, similar to
619 <code>pack(&quot;U&quot;)</code> and <code>unpack(&quot;U&quot;)</code>, <em>not</em> <code>pack(&quot;C&quot;)</code> and
620 <code>unpack(&quot;C&quot;)</code>. <code>pack(&quot;C&quot;)</code> and <code>unpack(&quot;C&quot;)</code> are methods for
621 emulating byte-oriented <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_chr"><code>chr()</code></a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ord"><code>ord()</code></a> on Unicode strings.
622 While these methods reveal the internal encoding of Unicode strings,
623 that is not something one normally needs to care about at all.</p>
624 </li>
625 <li>
626 <p>The bit string operators, <code>&amp; | ^ ~</code>, can operate on character data.
627 However, for backward compatibility, such as when using bit string
628 operations when characters are all less than 256 in ordinal value, one
629 should not use <code>~</code> (the bit complement) with characters of both
630 values less than 256 and values greater than 256. Most importantly,
631 DeMorgan's laws (<code>~($x|$y) eq ~$x&amp;~$y</code> and <code>~($x&amp;$y) eq ~$x|~$y</code>)
632 will not hold. The reason for this mathematical <em>faux pas</em> is that
633 the complement cannot return <strong>both</strong> the 8-bit (byte-wide) bit
634 complement <strong>and</strong> the full character-wide bit complement.</p>
635 </li>
636 <li>
637 <p>lc(), uc(), lcfirst(), and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ucfirst"><code>ucfirst()</code></a> work for the following cases:</p>
638 <ul>
639 <li>
640 <p>the case mapping is from a single Unicode character to another
641 single Unicode character, or</p>
642 </li>
643 <li>
644 <p>the case mapping is from a single Unicode character to more
645 than one Unicode character.</p>
646 </li>
647 </ul>
648 <p>Things to do with locales (Lithuanian, Turkish, Azeri) do <strong>not</strong> work
649 since Perl does not understand the concept of Unicode locales.</p>
650 <p>See the Unicode Technical Report #21, Case Mappings, for more details.</p>
651 </ul>
652 <ul>
653 <li>
654 <p>And finally, <code>scalar reverse()</code> reverses by character rather than by byte.</p>
655 </li>
656 </ul>
658 </p>
659 <h2><a name="userdefined_character_properties">User-Defined Character Properties</a></h2>
660 <p>You can define your own character properties by defining subroutines
661 whose names begin with ``In'' or ``Is''. The subroutines can be defined in
662 any package. The user-defined properties can be used in the regular
663 expression <code>\p</code> and <code>\P</code> constructs; if you are using a user-defined
664 property from a package other than the one you are in, you must specify
665 its package in the <code>\p</code> or <code>\P</code> construct.</p>
666 <pre>
667 # assuming property IsForeign defined in Lang::
668 package main; # property package name required
669 if ($txt =~ /\p{Lang::IsForeign}+/) { ... }</pre>
670 <pre>
671 package Lang; # property package name not required
672 if ($txt =~ /\p{IsForeign}+/) { ... }</pre>
673 <p>Note that the effect is compile-time and immutable once defined.</p>
674 <p>The subroutines must return a specially-formatted string, with one
675 or more newline-separated lines. Each line must be one of the following:</p>
676 <ul>
677 <li>
678 <p>Two hexadecimal numbers separated by horizontal whitespace (space or
679 tabular characters) denoting a range of Unicode code points to include.</p>
680 </li>
681 <li>
682 <p>Something to include, prefixed by ``+'': a built-in character
683 property (prefixed by ``utf8::'') or a user-defined character property,
684 to represent all the characters in that property; two hexadecimal code
685 points for a range; or a single hexadecimal code point.</p>
686 </li>
687 <li>
688 <p>Something to exclude, prefixed by ``-'': an existing character
689 property (prefixed by ``utf8::'') or a user-defined character property,
690 to represent all the characters in that property; two hexadecimal code
691 points for a range; or a single hexadecimal code point.</p>
692 </li>
693 <li>
694 <p>Something to negate, prefixed ``!'': an existing character
695 property (prefixed by ``utf8::'') or a user-defined character property,
696 to represent all the characters in that property; two hexadecimal code
697 points for a range; or a single hexadecimal code point.</p>
698 </li>
699 <li>
700 <p>Something to intersect with, prefixed by ``&amp;'': an existing character
701 property (prefixed by ``utf8::'') or a user-defined character property,
702 for all the characters except the characters in the property; two
703 hexadecimal code points for a range; or a single hexadecimal code point.</p>
704 </li>
705 </ul>
706 <p>For example, to define a property that covers both the Japanese
707 syllabaries (hiragana and katakana), you can define</p>
708 <pre>
709 sub InKana {
710 return &lt;&lt;END;
711 3040\t309F
712 30A0\t30FF
714 }</pre>
715 <p>Imagine that the here-doc end marker is at the beginning of the line.
716 Now you can use <code>\p{InKana}</code> and <code>\P{InKana}</code>.</p>
717 <p>You could also have used the existing block property names:</p>
718 <pre>
719 sub InKana {
720 return &lt;&lt;'END';
721 +utf8::InHiragana
722 +utf8::InKatakana
724 }</pre>
725 <p>Suppose you wanted to match only the allocated characters,
726 not the raw block ranges: in other words, you want to remove
727 the non-characters:</p>
728 <pre>
729 sub InKana {
730 return &lt;&lt;'END';
731 +utf8::InHiragana
732 +utf8::InKatakana
733 -utf8::IsCn
735 }</pre>
736 <p>The negation is useful for defining (surprise!) negated classes.</p>
737 <pre>
738 sub InNotKana {
739 return &lt;&lt;'END';
740 !utf8::InHiragana
741 -utf8::InKatakana
742 +utf8::IsCn
744 }</pre>
745 <p>Intersection is useful for getting the common characters matched by
746 two (or more) classes.</p>
747 <pre>
748 sub InFooAndBar {
749 return &lt;&lt;'END';
750 +main::Foo
751 &amp;main::Bar
753 }</pre>
754 <p>It's important to remember not to use ``&amp;'' for the first set -- that
755 would be intersecting with nothing (resulting in an empty set).</p>
756 <p>You can also define your own mappings to be used in the lc(),
757 lcfirst(), uc(), and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ucfirst"><code>ucfirst()</code></a> (or their string-inlined versions).
758 The principle is the same: define subroutines in the <code>main</code> package
759 with names like <code>ToLower</code> (for <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_lc"><code>lc()</code></a> and lcfirst()), <code>ToTitle</code> (for
760 the first character in ucfirst()), and <code>ToUpper</code> (for uc(), and the
761 rest of the characters in ucfirst()).</p>
762 <p>The string returned by the subroutines needs now to be three
763 hexadecimal numbers separated by tabulators: start of the source
764 range, end of the source range, and start of the destination range.
765 For example:</p>
766 <pre>
767 sub ToUpper {
768 return &lt;&lt;END;
769 0061\t0063\t0041
771 }</pre>
772 <p>defines an <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_uc"><code>uc()</code></a> mapping that causes only the characters ``a'', ``b'', and
773 ``c'' to be mapped to ``A'', ``B'', ``C'', all other characters will remain
774 unchanged.</p>
775 <p>If there is no source range to speak of, that is, the mapping is from
776 a single character to another single character, leave the end of the
777 source range empty, but the two tabulator characters are still needed.
778 For example:</p>
779 <pre>
780 sub ToLower {
781 return &lt;&lt;END;
782 0041\t\t0061
784 }</pre>
785 <p>defines a <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_lc"><code>lc()</code></a> mapping that causes only ``A'' to be mapped to ``a'', all
786 other characters will remain unchanged.</p>
787 <p>(For serious hackers only) If you want to introspect the default
788 mappings, you can find the data in the directory
789 <code>$Config{privlib}</code>/<em>unicore/To/</em>. The mapping data is returned as
790 the here-document, and the <code>utf8::ToSpecFoo</code> are special exception
791 mappings derived from &lt;$Config{privlib}&gt;/<em>unicore/SpecialCasing.txt</em>.
792 The <code>Digit</code> and <code>Fold</code> mappings that one can see in the directory
793 are not directly user-accessible, one can use either the
794 <code>Unicode::UCD</code> module, or just match case-insensitively (that's when
795 the <code>Fold</code> mapping is used).</p>
796 <p>A final note on the user-defined property tests and mappings: they
797 will be used only if the scalar has been marked as having Unicode
798 characters. Old byte-style strings will not be affected.</p>
800 </p>
801 <h2><a name="character_encodings_for_input_and_output">Character Encodings for Input and Output</a></h2>
802 <p>See <a href="file://C|\msysgit\mingw\html/lib/Encode.html">the Encode manpage</a>.</p>
804 </p>
805 <h2><a name="unicode_regular_expression_support_level">Unicode Regular Expression Support Level</a></h2>
806 <p>The following list of Unicode support for regular expressions describes
807 all the features currently supported. The references to ``Level N''
808 and the section numbers refer to the Unicode Technical Report 18,
809 ``Unicode Regular Expression Guidelines'', version 6 (Unicode 3.2.0,
810 Perl 5.8.0).</p>
811 <ul>
812 <li>
813 <p>Level 1 - Basic Unicode Support</p>
814 <pre>
815 2.1 Hex Notation - done [1]
816 Named Notation - done [2]
817 2.2 Categories - done [3][4]
818 2.3 Subtraction - MISSING [5][6]
819 2.4 Simple Word Boundaries - done [7]
820 2.5 Simple Loose Matches - done [8]
821 2.6 End of Line - MISSING [9][10]</pre>
822 <pre>
823 [ 1] \x{...}
824 [ 2] \N{...}
825 [ 3] . \p{...} \P{...}
826 [ 4] support for scripts (see UTR#24 Script Names), blocks,
827 binary properties, enumerated non-binary properties, and
828 numeric properties (as listed in UTR#18 Other Properties)
829 [ 5] have negation
830 [ 6] can use regular expression look-ahead [a]
831 or user-defined character properties [b] to emulate subtraction
832 [ 7] include Letters in word characters
833 [ 8] note that Perl does Full case-folding in matching, not Simple:
834 for example U+1F88 is equivalent with U+1F00 U+03B9,
835 not with 1F80. This difference matters for certain Greek
836 capital letters with certain modifiers: the Full case-folding
837 decomposes the letter, while the Simple case-folding would map
838 it to a single character.
839 [ 9] see UTR #13 Unicode Newline Guidelines
840 [10] should do ^ and $ also on \x{85}, \x{2028} and \x{2029}
841 (should also affect &lt;&gt;, $., and script line numbers)
842 (the \x{85}, \x{2028} and \x{2029} do match \s)</pre>
843 <p>[a] You can mimic class subtraction using lookahead.
844 For example, what UTR #18 might write as</p>
845 <pre>
846 [{Greek}-[{UNASSIGNED}]]</pre>
847 <p>in Perl can be written as:</p>
848 <pre>
849 (?!\p{Unassigned})\p{InGreekAndCoptic}
850 (?=\p{Assigned})\p{InGreekAndCoptic}</pre>
851 <p>But in this particular example, you probably really want</p>
852 <pre>
853 \p{GreekAndCoptic}</pre>
854 <p>which will match assigned characters known to be part of the Greek script.</p>
855 <p>Also see the Unicode::Regex::Set module, it does implement the full
856 UTR #18 grouping, intersection, union, and removal (subtraction) syntax.</p>
857 <p>[b] See <a href="#userdefined_character_properties">User-Defined Character Properties</a>.</p>
858 </li>
859 <li>
860 <p>Level 2 - Extended Unicode Support</p>
861 <pre>
862 3.1 Surrogates - MISSING [11]
863 3.2 Canonical Equivalents - MISSING [12][13]
864 3.3 Locale-Independent Graphemes - MISSING [14]
865 3.4 Locale-Independent Words - MISSING [15]
866 3.5 Locale-Independent Loose Matches - MISSING [16]</pre>
867 <pre>
868 [11] Surrogates are solely a UTF-16 concept and Perl's internal
869 representation is UTF-8. The Encode module does UTF-16, though.
870 [12] see UTR#15 Unicode Normalization
871 [13] have Unicode::Normalize but not integrated to regexes
872 [14] have \X but at this level . should equal that
873 [15] need three classes, not just \w and \W
874 [16] see UTR#21 Case Mappings</pre>
875 </li>
876 <li>
877 <p>Level 3 - Locale-Sensitive Support</p>
878 <pre>
879 4.1 Locale-Dependent Categories - MISSING
880 4.2 Locale-Dependent Graphemes - MISSING [16][17]
881 4.3 Locale-Dependent Words - MISSING
882 4.4 Locale-Dependent Loose Matches - MISSING
883 4.5 Locale-Dependent Ranges - MISSING</pre>
884 <pre>
885 [16] see UTR#10 Unicode Collation Algorithms
886 [17] have Unicode::Collate but not integrated to regexes</pre>
887 </li>
888 </ul>
890 </p>
891 <h2><a name="unicode_encodings">Unicode Encodings</a></h2>
892 <p>Unicode characters are assigned to <em>code points</em>, which are abstract
893 numbers. To use these numbers, various encodings are needed.</p>
894 <ul>
895 <li>
896 <p>UTF-8</p>
897 <p>UTF-8 is a variable-length (1 to 6 bytes, current character allocations
898 require 4 bytes), byte-order independent encoding. For ASCII (and we
899 really do mean 7-bit ASCII, not another 8-bit encoding), UTF-8 is
900 transparent.</p>
901 <p>The following table is from Unicode 3.2.</p>
902 <pre>
903 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte</pre>
904 <pre>
905 U+0000..U+007F 00..7F
906 U+0080..U+07FF C2..DF 80..BF
907 U+0800..U+0FFF E0 A0..BF 80..BF
908 U+1000..U+CFFF E1..EC 80..BF 80..BF
909 U+D000..U+D7FF ED 80..9F 80..BF
910 U+D800..U+DFFF ******* ill-formed *******
911 U+E000..U+FFFF EE..EF 80..BF 80..BF
912 U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
913 U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
914 U+100000..U+10FFFF F4 80..8F 80..BF 80..BF</pre>
915 <p>Note the <code>A0..BF</code> in <code>U+0800..U+0FFF</code>, the <code>80..9F</code> in
916 <code>U+D000...U+D7FF</code>, the <code>90..B</code>F in <code>U+10000..U+3FFFF</code>, and the
917 <code>80...8F</code> in <code>U+100000..U+10FFFF</code>. The ``gaps'' are caused by legal
918 UTF-8 avoiding non-shortest encodings: it is technically possible to
919 UTF-8-encode a single code point in different ways, but that is
920 explicitly forbidden, and the shortest possible encoding should always
921 be used. So that's what Perl does.</p>
922 <p>Another way to look at it is via bits:</p>
923 <pre>
924 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte</pre>
925 <pre>
926 0aaaaaaa 0aaaaaaa
927 00000bbbbbaaaaaa 110bbbbb 10aaaaaa
928 ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
929 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa</pre>
930 <p>As you can see, the continuation bytes all begin with <code>10</code>, and the
931 leading bits of the start byte tell how many bytes the are in the
932 encoded character.</p>
933 </li>
934 <li>
935 <p>UTF-EBCDIC</p>
936 <p>Like UTF-8 but EBCDIC-safe, in the way that UTF-8 is ASCII-safe.</p>
937 </li>
938 <li>
939 <p>UTF-16, UTF-16BE, UTF-16LE, Surrogates, and BOMs (Byte Order Marks)</p>
940 <p>The followings items are mostly for reference and general Unicode
941 knowledge, Perl doesn't use these constructs internally.</p>
942 <p>UTF-16 is a 2 or 4 byte encoding. The Unicode code points
943 <code>U+0000..U+FFFF</code> are stored in a single 16-bit unit, and the code
944 points <code>U+10000..U+10FFFF</code> in two 16-bit units. The latter case is
945 using <em>surrogates</em>, the first 16-bit unit being the <em>high
946 surrogate</em>, and the second being the <em>low surrogate</em>.</p>
947 <p>Surrogates are code points set aside to encode the <code>U+10000..U+10FFFF</code>
948 range of Unicode code points in pairs of 16-bit units. The <em>high
949 surrogates</em> are the range <code>U+D800..U+DBFF</code>, and the <em>low surrogates</em>
950 are the range <code>U+DC00..U+DFFF</code>. The surrogate encoding is</p>
951 <pre>
952 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
953 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;</pre>
954 <p>and the decoding is</p>
955 <pre>
956 $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);</pre>
957 <p>If you try to generate surrogates (for example by using chr()), you
958 will get a warning if warnings are turned on, because those code
959 points are not valid for a Unicode character.</p>
960 <p>Because of the 16-bitness, UTF-16 is byte-order dependent. UTF-16
961 itself can be used for in-memory computations, but if storage or
962 transfer is required either UTF-16BE (big-endian) or UTF-16LE
963 (little-endian) encodings must be chosen.</p>
964 <p>This introduces another problem: what if you just know that your data
965 is UTF-16, but you don't know which endianness? Byte Order Marks, or
966 BOMs, are a solution to this. A special character has been reserved
967 in Unicode to function as a byte order marker: the character with the
968 code point <code>U+FEFF</code> is the BOM.</p>
969 <p>The trick is that if you read a BOM, you will know the byte order,
970 since if it was written on a big-endian platform, you will read the
971 bytes <code>0xFE 0xFF</code>, but if it was written on a little-endian platform,
972 you will read the bytes <code>0xFF 0xFE</code>. (And if the originating platform
973 was writing in UTF-8, you will read the bytes <code>0xEF 0xBB 0xBF</code>.)</p>
974 <p>The way this trick works is that the character with the code point
975 <code>U+FFFE</code> is guaranteed not to be a valid Unicode character, so the
976 sequence of bytes <code>0xFF 0xFE</code> is unambiguously ``BOM, represented in
977 little-endian format'' and cannot be <code>U+FFFE</code>, represented in big-endian
978 format``.</p>
979 </li>
980 <li>
981 <p>UTF-32, UTF-32BE, UTF-32LE</p>
982 <p>The UTF-32 family is pretty much like the UTF-16 family, expect that
983 the units are 32-bit, and therefore the surrogate scheme is not
984 needed. The BOM signatures will be <code>0x00 0x00 0xFE 0xFF</code> for BE and
985 <code>0xFF 0xFE 0x00 0x00</code> for LE.</p>
986 </li>
987 <li>
988 <p>UCS-2, UCS-4</p>
989 <p>Encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit
990 encoding. Unlike UTF-16, UCS-2 is not extensible beyond <code>U+FFFF</code>,
991 because it does not use surrogates. UCS-4 is a 32-bit encoding,
992 functionally identical to UTF-32.</p>
993 </li>
994 <li>
995 <p>UTF-7</p>
996 <p>A seven-bit safe (non-eight-bit) encoding, which is useful if the
997 transport or storage is not eight-bit safe. Defined by RFC 2152.</p>
998 </li>
999 </ul>
1001 </p>
1002 <h2><a name="security_implications_of_unicode">Security Implications of Unicode</a></h2>
1003 <ul>
1004 <li>
1005 <p>Malformed UTF-8</p>
1006 <p>Unfortunately, the specification of UTF-8 leaves some room for
1007 interpretation of how many bytes of encoded output one should generate
1008 from one input Unicode character. Strictly speaking, the shortest
1009 possible sequence of UTF-8 bytes should be generated,
1010 because otherwise there is potential for an input buffer overflow at
1011 the receiving end of a UTF-8 connection. Perl always generates the
1012 shortest length UTF-8, and with warnings on Perl will warn about
1013 non-shortest length UTF-8 along with other malformations, such as the
1014 surrogates, which are not real Unicode code points.</p>
1015 </li>
1016 <li>
1017 <p>Regular expressions behave slightly differently between byte data and
1018 character (Unicode) data. For example, the ``word character'' character
1019 class <code>\w</code> will work differently depending on if data is eight-bit bytes
1020 or Unicode.</p>
1021 <p>In the first case, the set of <code>\w</code> characters is either small--the
1022 default set of alphabetic characters, digits, and the ``_''--or, if you
1023 are using a locale (see <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a>), the <code>\w</code> might contain a few
1024 more letters according to your language and country.</p>
1025 <p>In the second case, the <code>\w</code> set of characters is much, much larger.
1026 Most importantly, even in the set of the first 256 characters, it will
1027 probably match different characters: unlike most locales, which are
1028 specific to a language and country pair, Unicode classifies all the
1029 characters that are letters <em>somewhere</em> as <code>\w</code>. For example, your
1030 locale might not think that LATIN SMALL LETTER ETH is a letter (unless
1031 you happen to speak Icelandic), but Unicode does.</p>
1032 <p>As discussed elsewhere, Perl has one foot (two hooves?) planted in
1033 each of two worlds: the old world of bytes and the new world of
1034 characters, upgrading from bytes to characters when necessary.
1035 If your legacy code does not explicitly use Unicode, no automatic
1036 switch-over to characters should happen. Characters shouldn't get
1037 downgraded to bytes, either. It is possible to accidentally mix bytes
1038 and characters, however (see <a href="file://C|\msysgit\mingw\html/pod/perluniintro.html">the perluniintro manpage</a>), in which case <code>\w</code> in
1039 regular expressions might start behaving differently. Review your
1040 code. Use warnings and the <code>strict</code> pragma.</p>
1041 </li>
1042 </ul>
1044 </p>
1045 <h2><a name="unicode_in_perl_on_ebcdic">Unicode in Perl on EBCDIC</a></h2>
1046 <p>The way Unicode is handled on EBCDIC platforms is still
1047 experimental. On such platforms, references to UTF-8 encoding in this
1048 document and elsewhere should be read as meaning the UTF-EBCDIC
1049 specified in Unicode Technical Report 16, unless ASCII vs. EBCDIC issues
1050 are specifically discussed. There is no <code>utfebcdic</code> pragma or
1051 ``:utfebcdic'' layer; rather, ``utf8'' and ``:utf8'' are reused to mean
1052 the platform's ``natural'' 8-bit encoding of Unicode. See <a href="file://C|\msysgit\mingw\html/pod/perlebcdic.html">the perlebcdic manpage</a>
1053 for more discussion of the issues.</p>
1055 </p>
1056 <h2><a name="locales">Locales</a></h2>
1057 <p>Usually locale settings and Unicode do not affect each other, but
1058 there are a couple of exceptions:</p>
1059 <ul>
1060 <li>
1061 <p>You can enable automatic UTF-8-ification of your standard file
1062 handles, default <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open"><code>open()</code></a> layer, and <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item__argv"><code>@ARGV</code></a> by using either
1063 the <code>-C</code> command line switch or the <code>PERL_UNICODE</code> environment
1064 variable, see <a href="file://C|\msysgit\mingw\html/pod/perlrun.html">the perlrun manpage</a> for the documentation of the <code>-C</code> switch.</p>
1065 </li>
1066 <li>
1067 <p>Perl tries really hard to work both with Unicode and the old
1068 byte-oriented world. Most often this is nice, but sometimes Perl's
1069 straddling of the proverbial fence causes problems.</p>
1070 </li>
1071 </ul>
1073 </p>
1074 <h2><a name="when_unicode_does_not_happen">When Unicode Does Not Happen</a></h2>
1075 <p>While Perl does have extensive ways to input and output in Unicode,
1076 and few other 'entry points' like the @ARGV which can be interpreted
1077 as Unicode (UTF-8), there still are many places where Unicode (in some
1078 encoding or another) could be given as arguments or received as
1079 results, or both, but it is not.</p>
1080 <p>The following are such interfaces. For all of these interfaces Perl
1081 currently (as of 5.8.3) simply assumes byte strings both as arguments
1082 and results, or UTF-8 strings if the <code>encoding</code> pragma has been used.</p>
1083 <p>One reason why Perl does not attempt to resolve the role of Unicode in
1084 this cases is that the answers are highly dependent on the operating
1085 system and the file system(s). For example, whether filenames can be
1086 in Unicode, and in exactly what kind of encoding, is not exactly a
1087 portable concept. Similarly for the qx and system: how well will the
1088 'command line interface' (and which of them?) handle Unicode?</p>
1089 <ul>
1090 <li>
1091 <p>chdir, chmod, chown, chroot, exec, link, lstat, mkdir,
1092 rename, rmdir, stat, symlink, truncate, unlink, utime, -X</p>
1093 </li>
1094 <li>
1095 <p>%ENV</p>
1096 </li>
1097 <li>
1098 <p>glob (aka the &lt;*&gt;)</p>
1099 </li>
1100 <li>
1101 <p>open, opendir, sysopen</p>
1102 </li>
1103 <li>
1104 <p>qx (aka the backtick operator), system</p>
1105 </li>
1106 <li>
1107 <p>readdir, readlink</p>
1108 </li>
1109 </ul>
1111 </p>
1112 <h2><a name="forcing_unicode_in_perl__or_unforcing_unicode_in_perl_">Forcing Unicode in Perl (Or Unforcing Unicode in Perl)</a></h2>
1113 <p>Sometimes (see <a href="#when_unicode_does_not_happen">When Unicode Does Not Happen</a>) there are
1114 situations where you simply need to force Perl to believe that a byte
1115 string is UTF-8, or vice versa. The low-level calls
1116 utf8::upgrade($bytestring) and utf8::downgrade($utf8string) are
1117 the answers.</p>
1118 <p>Do not use them without careful thought, though: Perl may easily get
1119 very confused, angry, or even crash, if you suddenly change the 'nature'
1120 of scalar like that. Especially careful you have to be if you use the
1121 utf8::upgrade(): any random byte string is not valid UTF-8.</p>
1123 </p>
1124 <h2><a name="using_unicode_in_xs">Using Unicode in XS</a></h2>
1125 <p>If you want to handle Perl Unicode in XS extensions, you may find the
1126 following C APIs useful. See also <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#unicode_support">Unicode Support in the perlguts manpage</a> for an
1127 explanation about Unicode at the XS level, and <a href="file://C|\msysgit\mingw\html/pod/perlapi.html">the perlapi manpage</a> for the API
1128 details.</p>
1129 <ul>
1130 <li>
1131 <p><code>DO_UTF8(sv)</code> returns true if the <code>UTF8</code> flag is on and the bytes
1132 pragma is not in effect. <code>SvUTF8(sv)</code> returns true is the <code>UTF8</code>
1133 flag is on; the bytes pragma is ignored. The <code>UTF8</code> flag being on
1134 does <strong>not</strong> mean that there are any characters of code points greater
1135 than 255 (or 127) in the scalar or that there are even any characters
1136 in the scalar. What the <code>UTF8</code> flag means is that the sequence of
1137 octets in the representation of the scalar is the sequence of UTF-8
1138 encoded code points of the characters of a string. The <code>UTF8</code> flag
1139 being off means that each octet in this representation encodes a
1140 single character with code point 0..255 within the string. Perl's
1141 Unicode model is not to use UTF-8 until it is absolutely necessary.</p>
1142 </li>
1143 <li>
1144 <p><code>uvuni_to_utf8(buf, chr)</code> writes a Unicode character code point into
1145 a buffer encoding the code point as UTF-8, and returns a pointer
1146 pointing after the UTF-8 bytes.</p>
1147 </li>
1148 <li>
1149 <p><code>utf8_to_uvuni(buf, lenp)</code> reads UTF-8 encoded bytes from a buffer and
1150 returns the Unicode character code point and, optionally, the length of
1151 the UTF-8 byte sequence.</p>
1152 </li>
1153 <li>
1154 <p><code>utf8_length(start, end)</code> returns the length of the UTF-8 encoded buffer
1155 in characters. <code>sv_len_utf8(sv)</code> returns the length of the UTF-8 encoded
1156 scalar.</p>
1157 </li>
1158 <li>
1159 <p><code>sv_utf8_upgrade(sv)</code> converts the string of the scalar to its UTF-8
1160 encoded form. <code>sv_utf8_downgrade(sv)</code> does the opposite, if
1161 possible. <code>sv_utf8_encode(sv)</code> is like sv_utf8_upgrade except that
1162 it does not set the <code>UTF8</code> flag. <code>sv_utf8_decode()</code> does the
1163 opposite of <code>sv_utf8_encode()</code>. Note that none of these are to be
1164 used as general-purpose encoding or decoding interfaces: <code>use Encode</code>
1165 for that. <code>sv_utf8_upgrade()</code> is affected by the encoding pragma
1166 but <code>sv_utf8_downgrade()</code> is not (since the encoding pragma is
1167 designed to be a one-way street).</p>
1168 </li>
1169 <li>
1170 <p><code>is_utf8_char(s)</code> returns true if the pointer points to a valid UTF-8
1171 character.</p>
1172 </li>
1173 <li>
1174 <p><code>is_utf8_string(buf, len)</code> returns true if <code>len</code> bytes of the buffer
1175 are valid UTF-8.</p>
1176 </li>
1177 <li>
1178 <p><code>UTF8SKIP(buf)</code> will return the number of bytes in the UTF-8 encoded
1179 character in the buffer. <code>UNISKIP(chr)</code> will return the number of bytes
1180 required to UTF-8-encode the Unicode character code point. <code>UTF8SKIP()</code>
1181 is useful for example for iterating over the characters of a UTF-8
1182 encoded buffer; <code>UNISKIP()</code> is useful, for example, in computing
1183 the size required for a UTF-8 encoded buffer.</p>
1184 </li>
1185 <li>
1186 <p><code>utf8_distance(a, b)</code> will tell the distance in characters between the
1187 two pointers pointing to the same UTF-8 encoded buffer.</p>
1188 </li>
1189 <li>
1190 <p><code>utf8_hop(s, off)</code> will return a pointer to an UTF-8 encoded buffer
1191 that is <code>off</code> (positive or negative) Unicode characters displaced
1192 from the UTF-8 buffer <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_s"><code>s</code></a>. Be careful not to overstep the buffer:
1193 <code>utf8_hop()</code> will merrily run off the end or the beginning of the
1194 buffer if told to do so.</p>
1195 </li>
1196 <li>
1197 <p><code>pv_uni_display(dsv, spv, len, pvlim, flags)</code> and
1198 <code>sv_uni_display(dsv, ssv, pvlim, flags)</code> are useful for debugging the
1199 output of Unicode strings and scalars. By default they are useful
1200 only for debugging--they display <strong>all</strong> characters as hexadecimal code
1201 points--but with the flags <code>UNI_DISPLAY_ISPRINT</code>,
1202 <code>UNI_DISPLAY_BACKSLASH</code>, and <code>UNI_DISPLAY_QQ</code> you can make the
1203 output more readable.</p>
1204 </li>
1205 <li>
1206 <p><code>ibcmp_utf8(s1, pe1, u1, l1, u1, s2, pe2, l2, u2)</code> can be used to
1207 compare two strings case-insensitively in Unicode. For case-sensitive
1208 comparisons you can just use <code>memEQ()</code> and <code>memNE()</code> as usual.</p>
1209 </li>
1210 </ul>
1211 <p>For more information, see <a href="file://C|\msysgit\mingw\html/pod/perlapi.html">the perlapi manpage</a>, and <em>utf8.c</em> and <em>utf8.h</em>
1212 in the Perl source code distribution.</p>
1214 </p>
1215 <hr />
1216 <h1><a name="bugs">BUGS</a></h1>
1218 </p>
1219 <h2><a name="interaction_with_locales">Interaction with Locales</a></h2>
1220 <p>Use of locales with Unicode data may lead to odd results. Currently,
1221 Perl attempts to attach 8-bit locale info to characters in the range
1222 0..255, but this technique is demonstrably incorrect for locales that
1223 use characters above that range when mapped into Unicode. Perl's
1224 Unicode support will also tend to run slower. Use of locales with
1225 Unicode is discouraged.</p>
1227 </p>
1228 <h2><a name="interaction_with_extensions">Interaction with Extensions</a></h2>
1229 <p>When Perl exchanges data with an extension, the extension should be
1230 able to understand the UTF-8 flag and act accordingly. If the
1231 extension doesn't know about the flag, it's likely that the extension
1232 will return incorrectly-flagged data.</p>
1233 <p>So if you're working with Unicode data, consult the documentation of
1234 every module you're using if there are any issues with Unicode data
1235 exchange. If the documentation does not talk about Unicode at all,
1236 suspect the worst and probably look at the source to learn how the
1237 module is implemented. Modules written completely in Perl shouldn't
1238 cause problems. Modules that directly or indirectly access code written
1239 in other programming languages are at risk.</p>
1240 <p>For affected functions, the simple strategy to avoid data corruption is
1241 to always make the encoding of the exchanged data explicit. Choose an
1242 encoding that you know the extension can handle. Convert arguments passed
1243 to the extensions to that encoding and convert results back from that
1244 encoding. Write wrapper functions that do the conversions for you, so
1245 you can later change the functions when the extension catches up.</p>
1246 <p>To provide an example, let's say the popular Foo::Bar::escape_html
1247 function doesn't deal with Unicode data yet. The wrapper function
1248 would convert the argument to raw UTF-8 and convert the result back to
1249 Perl's internal representation like so:</p>
1250 <pre>
1251 sub my_escape_html ($) {
1252 my($what) = shift;
1253 return unless defined $what;
1254 Encode::decode_utf8(Foo::Bar::escape_html(Encode::encode_utf8($what)));
1255 }</pre>
1256 <p>Sometimes, when the extension does not convert data but just stores
1257 and retrieves them, you will be in a position to use the otherwise
1258 dangerous Encode::_utf8_on() function. Let's say the popular
1259 <code>Foo::Bar</code> extension, written in C, provides a <code>param</code> method that
1260 lets you store and retrieve data according to these prototypes:</p>
1261 <pre>
1262 $self-&gt;param($name, $value); # set a scalar
1263 $value = $self-&gt;param($name); # retrieve a scalar</pre>
1264 <p>If it does not yet provide support for any encoding, one could write a
1265 derived class with such a <code>param</code> method:</p>
1266 <pre>
1267 sub param {
1268 my($self,$name,$value) = @_;
1269 utf8::upgrade($name); # make sure it is UTF-8 encoded
1270 if (defined $value)
1271 utf8::upgrade($value); # make sure it is UTF-8 encoded
1272 return $self-&gt;SUPER::param($name,$value);
1273 } else {
1274 my $ret = $self-&gt;SUPER::param($name);
1275 Encode::_utf8_on($ret); # we know, it is UTF-8 encoded
1276 return $ret;
1278 }</pre>
1279 <p>Some extensions provide filters on data entry/exit points, such as
1280 DB_File::filter_store_key and family. Look out for such filters in
1281 the documentation of your extensions, they can make the transition to
1282 Unicode data much easier.</p>
1284 </p>
1285 <h2><a name="speed">Speed</a></h2>
1286 <p>Some functions are slower when working on UTF-8 encoded strings than
1287 on byte encoded strings. All functions that need to hop over
1288 characters such as length(), <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item_substr"><code>substr()</code></a> or index(), or matching regular
1289 expressions can work <strong>much</strong> faster when the underlying data are
1290 byte-encoded.</p>
1291 <p>In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1
1292 a caching scheme was introduced which will hopefully make the slowness
1293 somewhat less spectacular, at least for some operations. In general,
1294 operations with UTF-8 encoded strings are still slower. As an example,
1295 the Unicode properties (character classes) like <code>\p{Nd}</code> are known to
1296 be quite a bit slower (5-20 times) than their simpler counterparts
1297 like <code>\d</code> (then again, there 268 Unicode characters matching <code>Nd</code>
1298 compared with the 10 ASCII characters matching <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_d"><code>d</code></a>).</p>
1300 </p>
1301 <h2><a name="porting_code_from_perl5_6_x">Porting code from perl-5.6.X</a></h2>
1302 <p>Perl 5.8 has a different Unicode model from 5.6. In 5.6 the programmer
1303 was required to use the <code>utf8</code> pragma to declare that a given scope
1304 expected to deal with Unicode data and had to make sure that only
1305 Unicode data were reaching that scope. If you have code that is
1306 working with 5.6, you will need some of the following adjustments to
1307 your code. The examples are written such that the code will continue
1308 to work under 5.6, so you should be safe to try them out.</p>
1309 <ul>
1310 <li>
1311 <p>A filehandle that should read or write UTF-8</p>
1312 <pre>
1313 if ($] &gt; 5.007) {
1314 binmode $fh, &quot;:utf8&quot;;
1315 }</pre>
1316 </li>
1317 <li>
1318 <p>A scalar that is going to be passed to some extension</p>
1319 <p>Be it Compress::Zlib, Apache::Request or any extension that has no
1320 mention of Unicode in the manpage, you need to make sure that the
1321 UTF-8 flag is stripped off. Note that at the time of this writing
1322 (October 2002) the mentioned modules are not UTF-8-aware. Please
1323 check the documentation to verify if this is still true.</p>
1324 <pre>
1325 if ($] &gt; 5.007) {
1326 require Encode;
1327 $val = Encode::encode_utf8($val); # make octets
1328 }</pre>
1329 </li>
1330 <li>
1331 <p>A scalar we got back from an extension</p>
1332 <p>If you believe the scalar comes back as UTF-8, you will most likely
1333 want the UTF-8 flag restored:</p>
1334 <pre>
1335 if ($] &gt; 5.007) {
1336 require Encode;
1337 $val = Encode::decode_utf8($val);
1338 }</pre>
1339 </li>
1340 <li>
1341 <p>Same thing, if you are really sure it is UTF-8</p>
1342 <pre>
1343 if ($] &gt; 5.007) {
1344 require Encode;
1345 Encode::_utf8_on($val);
1346 }</pre>
1347 </li>
1348 <li>
1349 <p>A wrapper for fetchrow_array and fetchrow_hashref</p>
1350 <p>When the database contains only UTF-8, a wrapper function or method is
1351 a convenient way to replace all your fetchrow_array and
1352 fetchrow_hashref calls. A wrapper function will also make it easier to
1353 adapt to future enhancements in your database driver. Note that at the
1354 time of this writing (October 2002), the DBI has no standardized way
1355 to deal with UTF-8 data. Please check the documentation to verify if
1356 that is still true.</p>
1357 <pre>
1358 sub fetchrow {
1359 my($self, $sth, $what) = @_; # $what is one of fetchrow_{array,hashref}
1360 if ($] &lt; 5.007) {
1361 return $sth-&gt;$what;
1362 } else {
1363 require Encode;
1364 if (wantarray) {
1365 my @arr = $sth-&gt;$what;
1366 for (@arr) {
1367 defined &amp;&amp; /[^\000-\177]/ &amp;&amp; Encode::_utf8_on($_);
1369 return @arr;
1370 } else {
1371 my $ret = $sth-&gt;$what;
1372 if (ref $ret) {
1373 for my $k (keys %$ret) {
1374 defined &amp;&amp; /[^\000-\177]/ &amp;&amp; Encode::_utf8_on($_) for $ret-&gt;{$k};
1376 return $ret;
1377 } else {
1378 defined &amp;&amp; /[^\000-\177]/ &amp;&amp; Encode::_utf8_on($_) for $ret;
1379 return $ret;
1383 }</pre>
1384 </li>
1385 <li>
1386 <p>A large scalar that you know can only contain ASCII</p>
1387 <p>Scalars that contain only ASCII and are marked as UTF-8 are sometimes
1388 a drag to your program. If you recognize such a situation, just remove
1389 the UTF-8 flag:</p>
1390 <pre>
1391 utf8::downgrade($val) if $] &gt; 5.007;</pre>
1392 </li>
1393 </ul>
1395 </p>
1396 <hr />
1397 <h1><a name="see_also">SEE ALSO</a></h1>
1398 <p><a href="file://C|\msysgit\mingw\html/pod/perluniintro.html">the perluniintro manpage</a>, <a href="file://C|\msysgit\mingw\html/lib/encoding.html">the encoding manpage</a>, <a href="file://C|\msysgit\mingw\html/lib/Encode.html">the Encode manpage</a>, <a href="file://C|\msysgit\mingw\html/lib/open.html">the open manpage</a>, <a href="file://C|\msysgit\mingw\html/lib/utf8.html">the utf8 manpage</a>, <a href="file://C|\msysgit\mingw\html/lib/bytes.html">the bytes manpage</a>,
1399 <a href="file://C|\msysgit\mingw\html/pod/perlretut.html">the perlretut manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item____unicode_">${^UNICODE} in the perlvar manpage</a></p>
1400 <table border="0" width="100%" cellspacing="0" cellpadding="3">
1401 <tr><td class="block" style="background-color: #cccccc" valign="middle">
1402 <big><strong><span class="block">&nbsp;perlunicode - Unicode support in Perl</span></strong></big>
1403 </td></tr>
1404 </table>
1406 </body>
1408 </html>