3 perlunicode - Unicode support in Perl
7 =head2 Important Caveats
9 Unicode support is an extensive requirement. While Perl does not
10 implement the Unicode standard or the accompanying technical reports
11 from cover to cover, Perl does support many Unicode features.
15 =item Input and Output Disciplines
17 Perl knows when a filehandle uses Perl's internal Unicode encodings
18 (UTF-8 or UTF-EBCDIC) if the filehandle is opened with the ":utf8"
19 layer. Other encodings can be converted to Perl's encoding on input
20 or from Perl's encoding on output by use of the ":encoding(...)"
23 To indicate that Perl source itself is using a particular encoding,
26 =item Regular Expressions
28 The regular expression compiler produces polymorphic opcodes. That is,
29 the pattern adapts to the data and automatically switches to the Unicode
30 character scheme when presented with Unicode data--or instead uses
31 a traditional byte scheme when presented with byte data.
33 =item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts
35 As a compatibility measure, the C<use utf8> pragma must be explicitly
36 included to enable recognition of UTF-8 in the Perl scripts themselves
37 on ASCII-based machines or to recognize UTF-EBCDIC on EBCDIC-based
38 machines. B<These are the only times when an explicit C<use utf8>
41 You can also use the C<encoding> pragma to change the default encoding
42 of the data in your script; see L<encoding>.
46 =head2 Byte and Character Semantics
48 Beginning with version 5.6, Perl uses logically-wide characters to
49 represent strings internally.
51 In future, Perl-level operations will be expected to work with
52 characters rather than bytes.
54 However, as an interim compatibility measure, Perl aims to
55 provide a safe migration path from byte semantics to character
56 semantics for programs. For operations where Perl can unambiguously
57 decide that the input data are characters, Perl switches to
58 character semantics. For operations where this determination cannot
59 be made without additional information from the user, Perl decides in
60 favor of compatibility and chooses to use byte semantics.
62 This behavior preserves compatibility with earlier versions of Perl,
63 which allowed byte semantics in Perl operations only if
64 none of the program's inputs were marked as being as source of Unicode
65 character data. Such data may come from filehandles, from calls to
66 external programs, from information provided by the system (such as %ENV),
67 or from literals and constants in the source text.
69 On Windows platforms, if the C<-C> command line switch is used or the
70 ${^WIDE_SYSTEM_CALLS} global flag is set to C<1>, all system calls
71 will use the corresponding wide-character APIs. This feature is
72 available only on Windows to conform to the API standard already
73 established for that platform.
75 The C<bytes> pragma will always, regardless of platform, force byte
76 semantics in a particular lexical scope. See L<bytes>.
78 The C<utf8> pragma is primarily a compatibility device that enables
79 recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
80 Note that this pragma is only required while Perl defaults to byte
81 semantics; when character semantics become the default, this pragma
82 may become a no-op. See L<utf8>.
84 Unless explicitly stated, Perl operators use character semantics
85 for Unicode data and byte semantics for non-Unicode data.
86 The decision to use character semantics is made transparently. If
87 input data comes from a Unicode source--for example, if a character
88 encoding discipline is added to a filehandle or a literal Unicode
89 string constant appears in a program--character semantics apply.
90 Otherwise, byte semantics are in effect. The C<bytes> pragma should
91 be used to force byte semantics on Unicode data.
93 If strings operating under byte semantics and strings with Unicode
94 character data are concatenated, the new string will be upgraded to
95 I<ISO 8859-1 (Latin-1)>, even if the old Unicode string used EBCDIC.
96 This translation is done without regard to the system's native 8-bit
97 encoding, so to change this for systems with non-Latin-1 and
98 non-EBCDIC native encodings use the C<encoding> pragma. See
101 Under character semantics, many operations that formerly operated on
102 bytes now operate on characters. A character in Perl is
103 logically just a number ranging from 0 to 2**31 or so. Larger
104 characters may encode into longer sequences of bytes internally, but
105 this internal detail is mostly hidden for Perl code.
106 See L<perluniintro> for more.
108 =head2 Effects of Character Semantics
110 Character semantics have the following effects:
116 Strings--including hash keys--and regular expression patterns may
117 contain characters that have an ordinal value larger than 255.
119 If you use a Unicode editor to edit your program, Unicode characters
120 may occur directly within the literal strings in one of the various
121 Unicode encodings (UTF-8, UTF-EBCDIC, UCS-2, etc.), but will be recognized
122 as such and converted to Perl's internal representation only if the
123 appropriate L<encoding> is specified.
125 Unicode characters can also be added to a string by using the C<\x{...}>
126 notation. The Unicode code for the desired character, in
127 hexadecimal, should be placed in the braces. For instance, a smiley
128 face is C<\x{263A}>. This encoding scheme only works for characters
129 with a code of 0x100 or above.
133 use charnames ':full';
135 you can use the C<\N{...}> notation and put the official Unicode character
136 name within the braces, such as C<\N{WHITE SMILING FACE}>.
141 If an appropriate L<encoding> is specified, identifiers within the
142 Perl script may contain Unicode alphanumeric characters, including
143 ideographs. Perl does not currently attempt to canonicalize variable
148 Regular expressions match characters instead of bytes.
149 "." matches a character instead of a byte. The C<\C> pattern
150 is provided to force a match a single byte--a "C<char>" in C, hence C<\C>.
154 Character classes in regular expressions match characters instead of
155 bytes and match against the character properties specified in the
156 Unicode properties database. C<\w> can be used to match an
157 ideograph, for instance.
161 Named Unicode properties, scripts, and block ranges may be used like
162 character classes via the C<\p{}> "matches property" construct and
163 the C<\P{}> negation, "doesn't match property".
164 For instance, C<\p{Lu}> matches any
165 character with the Unicode "Lu" (Letter, uppercase) property, while
166 C<\p{M}> matches any character with an "M" (mark--accents and such)
167 property. Brackets are not required for single letter properties, so
168 C<\p{M}> is equivalent to C<\pM>. Many predefined properties are
169 available, such as C<\p{Mirrored}> and C<\p{Tibetan}>.
171 The official Unicode script and block names have spaces and dashes as
172 separators, but for convenience you can use dashes, spaces, or
173 underbars, and case is unimportant. It is
174 recommended, however, that for consistency you use the following naming:
175 the official Unicode script, property, or block name (see below for the
176 additional rules that apply to block names) with whitespace and dashes
177 removed, and the words "uppercase-first-lowercase-rest". "C<Latin-1
178 Supplement>" thus becomes "C<Latin1Supplement>".
180 You can also use negation in both C<\p{}> and C<\P{}> by introducing a caret
181 (^) between the first brace and the property name: C<\p{^Tamil}> is
182 equal to C<\P{Tamil}>.
184 Here are the basic Unicode General Category properties, followed by their
185 long form. You can use either; C<\p{Lu}> and C<\p{LowercaseLetter}>,
186 for instance, are identical.
208 Pc ConnectorPunctuation
212 Pi InitialPunctuation
213 (may behave like Ps or Pe depending on usage)
215 (may behave like Ps or Pe depending on usage)
227 Zp ParagraphSeparator
232 Cs Surrogate (not usable)
236 Single-letter properties match all characters in any of the
237 two-letter sub-properties starting with the same letter.
238 C<L&> is a special case, which is an alias for C<Ll>, C<Lu>, and C<Lt>.
240 Because Perl hides the need for the user to understand the internal
241 representation of Unicode characters, there is no need to implement the
242 somewhat messy concept of surrogates. C<Cs> is therefore not
245 Because scripts differ in their directionality--Hebrew is
246 written right to left, for example--Unicode supplies these properties:
251 BidiLRE Left-to-Right Embedding
252 BidiLRO Left-to-Right Override
254 BidiAL Right-to-Left Arabic
255 BidiRLE Right-to-Left Embedding
256 BidiRLO Right-to-Left Override
257 BidiPDF Pop Directional Format
258 BidiEN European Number
259 BidiES European Number Separator
260 BidiET European Number Terminator
262 BidiCS Common Number Separator
263 BidiNSM Non-Spacing Mark
264 BidiBN Boundary Neutral
265 BidiB Paragraph Separator
266 BidiS Segment Separator
268 BidiON Other Neutrals
270 For example, C<\p{BidiR}> matches characters that are normally
271 written right to left.
277 The script names which can be used by C<\p{...}> and C<\P{...}>,
278 such as in C<\p{Latin}> or C<\p{Cyrillic}>, are as follows:
325 Extended property classes can supplement the basic
326 properties, defined by the F<PropList> Unicode database:
341 LogicalOrderException
342 NoncharacterCodePoint
344 OtherDefaultIgnorableCodePoint
356 and there are further derived properties:
358 Alphabetic Lu + Ll + Lt + Lm + Lo + OtherAlphabetic
359 Lowercase Ll + OtherLowercase
360 Uppercase Lu + OtherUppercase
363 ID_Start Lu + Ll + Lt + Lm + Lo + Nl
364 ID_Continue ID_Start + Mn + Mc + Nd + Pc
367 Assigned Any non-Cn character (i.e. synonym for \P{Cn})
368 Unassigned Synonym for \p{Cn}
369 Common Any character (or unassigned code point)
370 not explicitly assigned to a script
372 For backward compatibility, all properties mentioned so far may have C<Is>
373 prepended to their name, so C<\P{IsLu}>, for example, is equal to C<\P{Lu}>.
377 In addition to B<scripts>, Unicode also defines B<blocks> of characters.
378 The difference between scripts and blocks is that the concept of
379 scripts is closer to natural languages, while the concept of blocks
380 is more of an artificial grouping based on groups of around 256
381 Unicode characters. For example, the C<Latin> script contains letters
382 from many blocks but does not contain all the characters from those
383 blocks. It does not, for example, contain digits, because digits are
384 shared across many scripts. Digits and similar groups, like
385 punctuation, are in a category called C<Common>.
387 For more about scripts, see the UTR #24:
389 http://www.unicode.org/unicode/reports/tr24/
391 For more about blocks, see:
393 http://www.unicode.org/Public/UNIDATA/Blocks.txt
395 Block names are given with the C<In> prefix. For example, the
396 Katakana block is referenced via C<\p{InKatakana}>. The C<In>
397 prefix may be omitted if there is no naming conflict with a script
398 or any other property, but it is recommended that C<In> always be used
401 These block names are supported:
403 InAlphabeticPresentationForms
405 InArabicPresentationFormsA
406 InArabicPresentationFormsB
417 InByzantineMusicalSymbols
419 InCJKCompatibilityForms
420 InCJKCompatibilityIdeographs
421 InCJKCompatibilityIdeographsSupplement
422 InCJKRadicalsSupplement
423 InCJKSymbolsAndPunctuation
424 InCJKUnifiedIdeographs
425 InCJKUnifiedIdeographsExtensionA
426 InCJKUnifiedIdeographsExtensionB
428 InCombiningDiacriticalMarks
429 InCombiningDiacriticalMarksforSymbols
434 InCyrillicSupplementary
438 InEnclosedAlphanumerics
439 InEnclosedCJKLettersAndMonths
449 InHalfwidthAndFullwidthForms
450 InHangulCompatibilityJamo
455 InHighPrivateUseSurrogates
459 InIdeographicDescriptionCharacters
464 InKatakanaPhoneticExtensions
469 InLatinExtendedAdditional
474 InMathematicalAlphanumericSymbols
475 InMathematicalOperators
476 InMiscellaneousMathematicalSymbolsA
477 InMiscellaneousMathematicalSymbolsB
478 InMiscellaneousSymbols
479 InMiscellaneousTechnical
486 InOpticalCharacterRecognition
492 InSpacingModifierLetters
494 InSuperscriptsAndSubscripts
495 InSupplementalArrowsA
496 InSupplementalArrowsB
497 InSupplementalMathematicalOperators
498 InSupplementaryPrivateUseAreaA
499 InSupplementaryPrivateUseAreaB
509 InUnifiedCanadianAboriginalSyllabics
518 The special pattern C<\X> matches any extended Unicode
519 sequence--"a combining character sequence" in Standardese--where the
520 first character is a base character and subsequent characters are mark
521 characters that apply to the base character. C<\X> is equivalent to
526 The C<tr///> operator translates characters instead of bytes. Note
527 that the C<tr///CU> functionality has been removed. For similar
528 functionality see pack('U0', ...) and pack('C0', ...).
532 Case translation operators use the Unicode case translation tables
533 when character input is provided. Note that C<uc()>, or C<\U> in
534 interpolated strings, translates to uppercase, while C<ucfirst>,
535 or C<\u> in interpolated strings, translates to titlecase in languages
536 that make the distinction.
540 Most operators that deal with positions or lengths in a string will
541 automatically switch to using character positions, including
542 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
543 C<sprintf()>, C<write()>, and C<length()>. Operators that
544 specifically do not switch include C<vec()>, C<pack()>, and
545 C<unpack()>. Operators that really don't care include C<chomp()>,
546 operators that treats strings as a bucket of bits such as C<sort()>,
547 and operators dealing with filenames.
551 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
552 since they are often used for byte-oriented formats. Again, think
553 "C<char>" in the C language. There is a new "C<U>" specifier
554 that converts between Unicode characters and integers.
558 The C<chr()> and C<ord()> functions work on characters, similar to
559 C<pack("U")> and C<unpack("U")>, I<not> C<pack("C")> and
560 C<unpack("C")>. C<pack("C")> and C<unpack("C")> are methods for
561 emulating byte-oriented C<chr()> and C<ord()> on Unicode strings.
562 While these methods reveal the internal encoding of Unicode strings,
563 that is not something one normally needs to care about at all.
567 The bit string operators, C<& | ^ ~>, can operate on character data.
568 However, for backward compatibility, such as when using bit string
569 operations when characters are all less than 256 in ordinal value, one
570 should not use C<~> (the bit complement) with characters of both
571 values less than 256 and values greater than 256. Most importantly,
572 DeMorgan's laws (C<~($x|$y) eq ~$x&~$y> and C<~($x&$y) eq ~$x|~$y>)
573 will not hold. The reason for this mathematical I<faux pas> is that
574 the complement cannot return B<both> the 8-bit (byte-wide) bit
575 complement B<and> the full character-wide bit complement.
579 lc(), uc(), lcfirst(), and ucfirst() work for the following cases:
585 the case mapping is from a single Unicode character to another
586 single Unicode character, or
590 the case mapping is from a single Unicode character to more
591 than one Unicode character.
595 The following cases do not yet work:
601 the "final sigma" (Greek), and
605 anything to with locales (Lithuanian, Turkish, Azeri).
609 See the Unicode Technical Report #21, Case Mappings, for more details.
613 And finally, C<scalar reverse()> reverses by character rather than by byte.
617 =head2 User-Defined Character Properties
619 You can define your own character properties by defining subroutines
620 whose names begin with "In" or "Is". The subroutines must be
621 visible in the package that uses the properties. The user-defined
622 properties can be used in the regular expression C<\p> and C<\P>
625 The subroutines must return a specially-formatted string, with one
626 or more newline-separated lines. Each line must be one of the following:
632 Two hexadecimal numbers separated by horizontal whitespace (space or
633 tabular characters) denoting a range of Unicode code points to include.
637 Something to include, prefixed by "+": a built-in character
638 property (prefixed by "utf8::"), to represent all the characters in that
639 property; two hexadecimal code points for a range; or a single
640 hexadecimal code point.
644 Something to exclude, prefixed by "-": an existing character
645 property (prefixed by "utf8::"), for all the characters in that
646 property; two hexadecimal code points for a range; or a single
647 hexadecimal code point.
651 Something to negate, prefixed "!": an existing character
652 property (prefixed by "utf8::") for all the characters except the
653 characters in the property; two hexadecimal code points for a range;
654 or a single hexadecimal code point.
658 For example, to define a property that covers both the Japanese
659 syllabaries (hiragana and katakana), you can define
668 Imagine that the here-doc end marker is at the beginning of the line.
669 Now you can use C<\p{InKana}> and C<\P{InKana}>.
671 You could also have used the existing block property names:
680 Suppose you wanted to match only the allocated characters,
681 not the raw block ranges: in other words, you want to remove
692 The negation is useful for defining (surprise!) negated classes.
702 =head2 Character Encodings for Input and Output
706 =head2 Unicode Regular Expression Support Level
708 The following list of Unicode support for regular expressions describes
709 all the features currently supported. The references to "Level N"
710 and the section numbers refer to the Unicode Technical Report 18,
711 "Unicode Regular Expression Guidelines".
717 Level 1 - Basic Unicode Support
719 2.1 Hex Notation - done [1]
720 Named Notation - done [2]
721 2.2 Categories - done [3][4]
722 2.3 Subtraction - MISSING [5][6]
723 2.4 Simple Word Boundaries - done [7]
724 2.5 Simple Loose Matches - done [8]
725 2.6 End of Line - MISSING [9][10]
729 [ 3] . \p{...} \P{...}
730 [ 4] now scripts (see UTR#24 Script Names) in addition to blocks
732 [ 6] can use regular expression look-ahead [a]
733 or user-defined character properties [b] to emulate subtraction
734 [ 7] include Letters in word characters
735 [ 8] note that Perl does Full case-folding in matching, not Simple:
736 for example U+1F88 is equivalent with U+1F000 U+03B9,
737 not with 1F80. This difference matters for certain Greek
738 capital letters with certain modifiers: the Full case-folding
739 decomposes the letter, while the Simple case-folding would map
740 it to a single character.
741 [ 9] see UTR#13 Unicode Newline Guidelines
742 [10] should do ^ and $ also on \x{85}, \x{2028} and \x{2029})
743 (should also affect <>, $., and script line numbers)
744 (the \x{85}, \x{2028} and \x{2029} do match \s)
746 [a] You can mimic class subtraction using lookahead.
747 For example, what TR18 might write as
749 [{Greek}-[{UNASSIGNED}]]
751 in Perl can be written as:
753 (?!\p{Unassigned})\p{InGreekAndCoptic}
754 (?=\p{Assigned})\p{InGreekAndCoptic}
756 But in this particular example, you probably really want
760 which will match assigned characters known to be part of the Greek script.
762 [b] See L</User-defined Character Properties>.
766 Level 2 - Extended Unicode Support
768 3.1 Surrogates - MISSING
769 3.2 Canonical Equivalents - MISSING [11][12]
770 3.3 Locale-Independent Graphemes - MISSING [13]
771 3.4 Locale-Independent Words - MISSING [14]
772 3.5 Locale-Independent Loose Matches - MISSING [15]
774 [11] see UTR#15 Unicode Normalization
775 [12] have Unicode::Normalize but not integrated to regexes
776 [13] have \X but at this level . should equal that
777 [14] need three classes, not just \w and \W
778 [15] see UTR#21 Case Mappings
782 Level 3 - Locale-Sensitive Support
784 4.1 Locale-Dependent Categories - MISSING
785 4.2 Locale-Dependent Graphemes - MISSING [16][17]
786 4.3 Locale-Dependent Words - MISSING
787 4.4 Locale-Dependent Loose Matches - MISSING
788 4.5 Locale-Dependent Ranges - MISSING
790 [16] see UTR#10 Unicode Collation Algorithms
791 [17] have Unicode::Collate but not integrated to regexes
795 =head2 Unicode Encodings
797 Unicode characters are assigned to I<code points>, which are abstract
798 numbers. To use these numbers, various encodings are needed.
806 UTF-8 is a variable-length (1 to 6 bytes, current character allocations
807 require 4 bytes), byte-order independent encoding. For ASCII (and we
808 really do mean 7-bit ASCII, not another 8-bit encoding), UTF-8 is
811 The following table is from Unicode 3.2.
813 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
815 U+0000..U+007F 00..7F
816 U+0080..U+07FF C2..DF 80..BF
817 U+0800..U+0FFF E0 A0..BF 80..BF
818 U+1000..U+CFFF E1..EC 80..BF 80..BF
819 U+D000..U+D7FF ED 80..9F 80..BF
820 U+D800..U+DFFF ******* ill-formed *******
821 U+E000..U+FFFF EE..EF 80..BF 80..BF
822 U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
823 U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
824 U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
826 Note the C<A0..BF> in C<U+0800..U+0FFF>, the C<80..9F> in
827 C<U+D000...U+D7FF>, the C<90..B>F in C<U+10000..U+3FFFF>, and the
828 C<80...8F> in C<U+100000..U+10FFFF>. The "gaps" are caused by legal
829 UTF-8 avoiding non-shortest encodings: it is technically possible to
830 UTF-8-encode a single code point in different ways, but that is
831 explicitly forbidden, and the shortest possible encoding should always
832 be used. So that's what Perl does.
834 Another way to look at it is via bits:
836 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
839 00000bbbbbaaaaaa 110bbbbb 10aaaaaa
840 ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
841 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa
843 As you can see, the continuation bytes all begin with C<10>, and the
844 leading bits of the start byte tell how many bytes the are in the
851 Like UTF-8 but EBCDIC-safe, in the way that UTF-8 is ASCII-safe.
855 UTF-16, UTF-16BE, UTF16-LE, Surrogates, and BOMs (Byte Order Marks)
857 The followings items are mostly for reference, Perl doesn't
860 UTF-16 is a 2 or 4 byte encoding. The Unicode code points
861 C<U+0000..U+FFFF> are stored in a single 16-bit unit, and the code points
862 C<U+10000..U+10FFFF> in two 16-bit units. The latter case is
863 using I<surrogates>, the first 16-bit unit being the I<high
864 surrogate>, and the second being the I<low surrogate>.
866 Surrogates are code points set aside to encode the C<U+10000..U+10FFFF>
867 range of Unicode code points in pairs of 16-bit units. The I<high
868 surrogates> are the range C<U+D800..U+DBFF>, and the I<low surrogates>
869 are the range C<U+DC00..U+DFFF>. The surrogate encoding is
871 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
872 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
876 $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
878 If you try to generate surrogates (for example by using chr()), you
879 will get a warning if warnings are turned on, because those code
880 points are not valid for a Unicode character.
882 Because of the 16-bitness, UTF-16 is byte-order dependent. UTF-16
883 itself can be used for in-memory computations, but if storage or
884 transfer is required either UTF-16BE (big-endian) or UTF-16LE
885 (little-endian) encodings must be chosen.
887 This introduces another problem: what if you just know that your data
888 is UTF-16, but you don't know which endianness? Byte Order Marks, or
889 BOMs, are a solution to this. A special character has been reserved
890 in Unicode to function as a byte order marker: the character with the
891 code point C<U+FEFF> is the BOM.
893 The trick is that if you read a BOM, you will know the byte order,
894 since if it was written on a big-endian platform, you will read the
895 bytes C<0xFE 0xFF>, but if it was written on a little-endian platform,
896 you will read the bytes C<0xFF 0xFE>. (And if the originating platform
897 was writing in UTF-8, you will read the bytes C<0xEF 0xBB 0xBF>.)
899 The way this trick works is that the character with the code point
900 C<U+FFFE> is guaranteed not to be a valid Unicode character, so the
901 sequence of bytes C<0xFF 0xFE> is unambiguously "BOM, represented in
902 little-endian format" and cannot be "C<U+FFFE>, represented in big-endian
907 UTF-32, UTF-32BE, UTF32-LE
909 The UTF-32 family is pretty much like the UTF-16 family, expect that
910 the units are 32-bit, and therefore the surrogate scheme is not
911 needed. The BOM signatures will be C<0x00 0x00 0xFE 0xFF> for BE and
912 C<0xFF 0xFE 0x00 0x00> for LE.
918 Encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit
919 encoding. Unlike UTF-16, UCS-2 is not extensible beyond C<U+FFFF>,
920 because it does not use surrogates. UCS-4 is a 32-bit encoding,
921 functionally identical to UTF-32.
927 A seven-bit safe (non-eight-bit) encoding, which is useful if the
928 transport or storage is not eight-bit safe. Defined by RFC 2152.
932 =head2 Security Implications of Unicode
940 Unfortunately, the specification of UTF-8 leaves some room for
941 interpretation of how many bytes of encoded output one should generate
942 from one input Unicode character. Strictly speaking, the shortest
943 possible sequence of UTF-8 bytes should be generated,
944 because otherwise there is potential for an input buffer overflow at
945 the receiving end of a UTF-8 connection. Perl always generates the
946 shortest length UTF-8, and with warnings on Perl will warn about
947 non-shortest length UTF-8 along with other malformations, such as the
948 surrogates, which are not real Unicode code points.
952 Regular expressions behave slightly differently between byte data and
953 character (Unicode) data. For example, the "word character" character
954 class C<\w> will work differently depending on if data is eight-bit bytes
957 In the first case, the set of C<\w> characters is either small--the
958 default set of alphabetic characters, digits, and the "_"--or, if you
959 are using a locale (see L<perllocale>), the C<\w> might contain a few
960 more letters according to your language and country.
962 In the second case, the C<\w> set of characters is much, much larger.
963 Most importantly, even in the set of the first 256 characters, it
964 will probably match different characters: unlike most locales,
965 which are specific to a language and country pair, Unicode classifies all
966 the characters that are letters as C<\w>. For example, your locale might
967 not think that LATIN SMALL LETTER ETH is a letter (unless you happen
968 to speak Icelandic), but Unicode does.
970 As discussed elsewhere, Perl has one foot (two hooves?) planted in
971 each of two worlds: the old world of bytes and the new
972 world of characters, upgrading from bytes to characters when necessary.
973 If your legacy code does not explicitly use Unicode, no automatic
974 switch-over to characters should happen. Characters shouldn't get
975 downgraded to bytes, either. It is possible to accidentally mix
976 bytes and characters, however (see L<perluniintro>), in which case
977 C<\w> in regular expressions might start behaving differently. Review
982 =head2 Unicode in Perl on EBCDIC
984 The way Unicode is handled on EBCDIC platforms is still
985 experimental. On such platforms, references to UTF-8 encoding in this
986 document and elsewhere should be read as meaning the UTF-EBCDIC
987 specified in Unicode Technical Report 16, unless ASCII vs. EBCDIC issues
988 are specifically discussed. There is no C<utfebcdic> pragma or
989 ":utfebcdic" layer; rather, "utf8" and ":utf8" are reused to mean
990 the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic>
991 for more discussion of the issues.
995 Usually locale settings and Unicode do not affect each other, but
996 there are a couple of exceptions:
1002 If your locale environment variables (LANGUAGE, LC_ALL, LC_CTYPE, LANG)
1003 contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
1004 the default encodings of your STDIN, STDOUT, and STDERR, and of
1005 B<any subsequent file open>, are considered to be UTF-8.
1009 Perl tries really hard to work both with Unicode and the old
1010 byte-oriented world. Most often this is nice, but sometimes Perl's
1011 straddling of the proverbial fence causes problems.
1015 =head2 Using Unicode in XS
1017 If you want to handle Perl Unicode in XS extensions, you may find
1018 the following C APIs useful. See L<perlapi> for details.
1024 C<DO_UTF8(sv)> returns true if the C<UTF8> flag is on and the bytes pragma
1025 is not in effect. C<SvUTF8(sv)> returns true is the C<UTF8> flag is on; the
1026 bytes pragma is ignored. The C<UTF8> flag being on does B<not> mean that
1027 there are any characters of code points greater than 255 (or 127) in
1028 the scalar or that there are even any characters in the scalar.
1029 What the C<UTF8> flag means is that the sequence of octets in the
1030 representation of the scalar is the sequence of UTF-8 encoded
1031 code points of the characters of a string. The C<UTF8> flag being
1032 off means that each octet in this representation encodes a single
1033 character with code point 0..255 within the string. Perl's Unicode
1034 model is not to use UTF-8 until it is absolutely necessary.
1038 C<uvuni_to_utf8(buf, chr>) writes a Unicode character code point into a
1039 buffer encoding the code point as UTF-8, and returns a pointer
1040 pointing after the UTF-8 bytes.
1044 C<utf8_to_uvuni(buf, lenp)> reads UTF-8 encoded bytes from a buffer and
1045 returns the Unicode character code point and, optionally, the length of
1046 the UTF-8 byte sequence.
1050 C<utf8_length(start, end)> returns the length of the UTF-8 encoded buffer
1051 in characters. C<sv_len_utf8(sv)> returns the length of the UTF-8 encoded
1056 C<sv_utf8_upgrade(sv)> converts the string of the scalar to its UTF-8
1057 encoded form. C<sv_utf8_downgrade(sv)> does the opposite, if
1058 possible. C<sv_utf8_encode(sv)> is like sv_utf8_upgrade except that
1059 it does not set the C<UTF8> flag. C<sv_utf8_decode()> does the
1060 opposite of C<sv_utf8_encode()>. Note that none of these are to be
1061 used as general-purpose encoding or decoding interfaces: C<use Encode>
1062 for that. C<sv_utf8_upgrade()> is affected by the encoding pragma
1063 but C<sv_utf8_downgrade()> is not (since the encoding pragma is
1064 designed to be a one-way street).
1068 C<is_utf8_char(s)> returns true if the pointer points to a valid UTF-8
1073 C<is_utf8_string(buf, len)> returns true if C<len> bytes of the buffer
1078 C<UTF8SKIP(buf)> will return the number of bytes in the UTF-8 encoded
1079 character in the buffer. C<UNISKIP(chr)> will return the number of bytes
1080 required to UTF-8-encode the Unicode character code point. C<UTF8SKIP()>
1081 is useful for example for iterating over the characters of a UTF-8
1082 encoded buffer; C<UNISKIP()> is useful, for example, in computing
1083 the size required for a UTF-8 encoded buffer.
1087 C<utf8_distance(a, b)> will tell the distance in characters between the
1088 two pointers pointing to the same UTF-8 encoded buffer.
1092 C<utf8_hop(s, off)> will return a pointer to an UTF-8 encoded buffer
1093 that is C<off> (positive or negative) Unicode characters displaced
1094 from the UTF-8 buffer C<s>. Be careful not to overstep the buffer:
1095 C<utf8_hop()> will merrily run off the end or the beginning of the
1096 buffer if told to do so.
1100 C<pv_uni_display(dsv, spv, len, pvlim, flags)> and
1101 C<sv_uni_display(dsv, ssv, pvlim, flags)> are useful for debugging the
1102 output of Unicode strings and scalars. By default they are useful
1103 only for debugging--they display B<all> characters as hexadecimal code
1104 points--but with the flags C<UNI_DISPLAY_ISPRINT> and
1105 C<UNI_DISPLAY_BACKSLASH> you can make the output more readable.
1109 C<ibcmp_utf8(s1, pe1, u1, l1, u1, s2, pe2, l2, u2)> can be used to
1110 compare two strings case-insensitively in Unicode. For case-sensitive
1111 comparisons you can just use C<memEQ()> and C<memNE()> as usual.
1115 For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h>
1116 in the Perl source code distribution.
1120 =head2 Interaction with Locales
1122 Use of locales with Unicode data may lead to odd results. Currently,
1123 Perl attempts to attach 8-bit locale info to characters in the range
1124 0..255, but this technique is demonstrably incorrect for locales that
1125 use characters above that range when mapped into Unicode. Perl's
1126 Unicode support will also tend to run slower. Use of locales with
1127 Unicode is discouraged.
1129 =head2 Interaction with Extensions
1131 When Perl exchanges data with an extension, the extension should be
1132 able to understand the UTF-8 flag and act accordingly. If the
1133 extension doesn't know about the flag, it's likely that the extension
1134 will return incorrectly-flagged data.
1136 So if you're working with Unicode data, consult the documentation of
1137 every module you're using if there are any issues with Unicode data
1138 exchange. If the documentation does not talk about Unicode at all,
1139 suspect the worst and probably look at the source to learn how the
1140 module is implemented. Modules written completely in Perl shouldn't
1141 cause problems. Modules that directly or indirectly access code written
1142 in other programming languages are at risk.
1144 For affected functions, the simple strategy to avoid data corruption is
1145 to always make the encoding of the exchanged data explicit. Choose an
1146 encoding that you know the extension can handle. Convert arguments passed
1147 to the extensions to that encoding and convert results back from that
1148 encoding. Write wrapper functions that do the conversions for you, so
1149 you can later change the functions when the extension catches up.
1151 To provide an example, let's say the popular Foo::Bar::escape_html
1152 function doesn't deal with Unicode data yet. The wrapper function
1153 would convert the argument to raw UTF-8 and convert the result back to
1154 Perl's internal representation like so:
1156 sub my_escape_html ($) {
1158 return unless defined $what;
1159 Encode::decode_utf8(Foo::Bar::escape_html(Encode::encode_utf8($what)));
1162 Sometimes, when the extension does not convert data but just stores
1163 and retrieves them, you will be in a position to use the otherwise
1164 dangerous Encode::_utf8_on() function. Let's say the popular
1165 C<Foo::Bar> extension, written in C, provides a C<param> method that
1166 lets you store and retrieve data according to these prototypes:
1168 $self->param($name, $value); # set a scalar
1169 $value = $self->param($name); # retrieve a scalar
1171 If it does not yet provide support for any encoding, one could write a
1172 derived class with such a C<param> method:
1175 my($self,$name,$value) = @_;
1176 utf8::upgrade($name); # make sure it is UTF-8 encoded
1178 utf8::upgrade($value); # make sure it is UTF-8 encoded
1179 return $self->SUPER::param($name,$value);
1181 my $ret = $self->SUPER::param($name);
1182 Encode::_utf8_on($ret); # we know, it is UTF-8 encoded
1187 Some extensions provide filters on data entry/exit points, such as
1188 DB_File::filter_store_key and family. Look out for such filters in
1189 the documentation of your extensions, they can make the transition to
1190 Unicode data much easier.
1194 Some functions are slower when working on UTF-8 encoded strings than
1195 on byte encoded strings. All functions that need to hop over
1196 characters such as length(), substr() or index() can work B<much>
1197 faster when the underlying data are byte-encoded. Witness the
1198 following benchmark:
1204 our $u = our $b = "x" x $l;
1205 substr($u,0,1) = "\x{100}";
1207 LENGTH_B => q{ length($b) },
1208 LENGTH_U => q{ length($u) },
1209 SUBSTR_B => q{ substr($b, $l/4, $l/2) },
1210 SUBSTR_U => q{ substr($u, $l/4, $l/2) },
1213 Benchmark: running LENGTH_B, LENGTH_U, SUBSTR_B, SUBSTR_U for at least 2 CPU seconds...
1214 LENGTH_B: 2 wallclock secs ( 2.36 usr + 0.00 sys = 2.36 CPU) @ 5649983.05/s (n=13333960)
1215 LENGTH_U: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 12155.45/s (n=25648)
1216 SUBSTR_B: 3 wallclock secs ( 2.16 usr + 0.00 sys = 2.16 CPU) @ 374480.09/s (n=808877)
1217 SUBSTR_U: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 6791.00/s (n=14329)
1219 The numbers show an incredible slowness on long UTF-8 strings. You
1220 should carefully avoid using these functions in tight loops. If you
1221 want to iterate over characters, the superior coding technique would
1222 split the characters into an array instead of using substr, as the following
1229 our $u = our $b = "x" x $l;
1230 substr($u,0,1) = "\x{100}";
1232 SPLIT_B => q{ for my $c (split //, $b){} },
1233 SPLIT_U => q{ for my $c (split //, $u){} },
1234 SUBSTR_B => q{ for my $i (0..length($b)-1){my $c = substr($b,$i,1);} },
1235 SUBSTR_U => q{ for my $i (0..length($u)-1){my $c = substr($u,$i,1);} },
1238 Benchmark: running SPLIT_B, SPLIT_U, SUBSTR_B, SUBSTR_U for at least 5 CPU seconds...
1239 SPLIT_B: 6 wallclock secs ( 5.29 usr + 0.00 sys = 5.29 CPU) @ 56.14/s (n=297)
1240 SPLIT_U: 5 wallclock secs ( 5.17 usr + 0.01 sys = 5.18 CPU) @ 55.21/s (n=286)
1241 SUBSTR_B: 5 wallclock secs ( 5.34 usr + 0.00 sys = 5.34 CPU) @ 123.22/s (n=658)
1242 SUBSTR_U: 7 wallclock secs ( 6.20 usr + 0.00 sys = 6.20 CPU) @ 0.81/s (n=5)
1244 Even though the algorithm based on C<substr()> is faster than
1245 C<split()> for byte-encoded data, it pales in comparison to the speed
1246 of C<split()> when used with UTF-8 data.
1250 L<perluniintro>, L<encoding>, L<Encode>, L<open>, L<utf8>, L<bytes>,
1251 L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">