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 A filehandle can be marked as containing perl's internal Unicode
18 encoding (UTF-8 or UTF-EBCDIC) by opening it with the ":utf8" layer.
19 Other encodings can be converted to perl's encoding on input, or from
20 perl's encoding on output by use of the ":encoding(...)" layer.
23 In some filesystems (for example Microsoft NTFS and Apple HFS+) the
24 filenames are in UTF-8 . By using opendir() and File::Glob you can
25 make readdir() and glob() to return the filenames as Unicode, see
26 L<perlfunc/opendir> and L<File::Glob> for details.
28 To mark the Perl source itself as being in a particular encoding,
31 =item Regular Expressions
33 The regular expression compiler produces polymorphic opcodes. That is,
34 the pattern adapts to the data and automatically switch to the Unicode
35 character scheme when presented with Unicode data, or a traditional
36 byte scheme when presented with byte data.
38 =item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts
40 As a compatibility measure, this pragma must be explicitly used to
41 enable recognition of UTF-8 in the Perl scripts themselves on ASCII
42 based machines, or to recognize UTF-EBCDIC on EBCDIC based machines.
43 B<NOTE: this should be the only place where an explicit C<use utf8>
46 You can also use the C<encoding> pragma to change the default encoding
47 of the data in your script; see L<encoding>.
51 =head2 Byte and Character semantics
53 Beginning with version 5.6, Perl uses logically wide characters to
54 represent strings internally.
56 In future, Perl-level operations can be expected to work with
57 characters rather than bytes, in general.
59 However, as strictly an interim compatibility measure, Perl aims to
60 provide a safe migration path from byte semantics to character
61 semantics for programs. For operations where Perl can unambiguously
62 decide that the input data is characters, Perl now switches to
63 character semantics. For operations where this determination cannot
64 be made without additional information from the user, Perl decides in
65 favor of compatibility, and chooses to use byte semantics.
67 This behavior preserves compatibility with earlier versions of Perl,
68 which allowed byte semantics in Perl operations, but only as long as
69 none of the program's inputs are marked as being as source of Unicode
70 character data. Such data may come from filehandles, from calls to
71 external programs, from information provided by the system (such as %ENV),
72 or from literals and constants in the source text.
74 On Windows platforms, if the C<-C> command line switch is used, (or the
75 ${^WIDE_SYSTEM_CALLS} global flag is set to C<1>), all system calls
76 will use the corresponding wide character APIs. Note that this is
77 currently only implemented on Windows since other platforms lack an
78 API standard on this area.
80 Regardless of the above, the C<bytes> pragma can always be used to
81 force byte semantics in a particular lexical scope. See L<bytes>.
83 The C<utf8> pragma is primarily a compatibility device that enables
84 recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
85 Note that this pragma is only required until a future version of Perl
86 in which character semantics will become the default. This pragma may
87 then become a no-op. See L<utf8>.
89 Unless mentioned otherwise, Perl operators will use character semantics
90 when they are dealing with Unicode data, and byte semantics otherwise.
91 Thus, character semantics for these operations apply transparently; if
92 the input data came from a Unicode source (for example, by adding a
93 character encoding discipline to the filehandle whence it came, or a
94 literal Unicode string constant in the program), character semantics
95 apply; otherwise, byte semantics are in effect. To force byte semantics
96 on Unicode data, the C<bytes> pragma should be used.
98 Notice that if you concatenate strings with byte semantics and strings
99 with Unicode character data, the bytes will by default be upgraded
100 I<as if they were ISO 8859-1 (Latin-1)> (or if in EBCDIC, after a
101 translation to ISO 8859-1). This is done without regard to the
102 system's native 8-bit encoding, so to change this for systems with
103 non-Latin-1 (or non-EBCDIC) native encodings, use the C<encoding>
104 pragma, see L<encoding>.
106 Under character semantics, many operations that formerly operated on
107 bytes change to operating on characters. A character in Perl is
108 logically just a number ranging from 0 to 2**31 or so. Larger
109 characters may encode to longer sequences of bytes internally, but
110 this is just an internal detail which is hidden at the Perl level.
111 See L<perluniintro> for more on this.
113 =head2 Effects of character semantics
115 Character semantics have the following effects:
121 Strings (including hash keys) and regular expression patterns may
122 contain characters that have an ordinal value larger than 255.
124 If you use a Unicode editor to edit your program, Unicode characters
125 may occur directly within the literal strings in one of the various
126 Unicode encodings (UTF-8, UTF-EBCDIC, UCS-2, etc.), but are recognized
127 as such (and converted to Perl's internal representation) only if the
128 appropriate L<encoding> is specified.
130 You can also get Unicode characters into a string by using the C<\x{...}>
131 notation, putting the Unicode code for the desired character, in
132 hexadecimal, into the curlies. For instance, a smiley face is C<\x{263A}>.
133 This works only for characters with a code 0x100 and above.
137 use charnames ':full';
139 you can use the C<\N{...}> notation, putting the official Unicode character
140 name within the curlies. For example, C<\N{WHITE SMILING FACE}>.
141 This works for all characters that have names.
145 If an appropriate L<encoding> is specified, identifiers within the
146 Perl script may contain Unicode alphanumeric characters, including
147 ideographs. (You are currently on your own when it comes to using the
148 canonical forms of characters--Perl doesn't (yet) attempt to
149 canonicalize variable names for you.)
153 Regular expressions match characters instead of bytes. For instance,
154 "." matches a character instead of a byte. (However, the C<\C> pattern
155 is provided to force a match a single byte ("C<char>" in C, hence C<\C>).)
159 Character classes in regular expressions match characters instead of
160 bytes, and match against the character properties specified in the
161 Unicode properties database. So C<\w> can be used to match an
162 ideograph, for instance.
166 Named Unicode properties, scripts, and block ranges may be used like
167 character classes via the new C<\p{}> (matches property) and C<\P{}>
168 (doesn't match property) constructs. For instance, C<\p{Lu}> matches any
169 character with the Unicode "Lu" (Letter, uppercase) property, while
170 C<\p{M}> matches any character with a "M" (mark -- accents and such)
171 property. Single letter properties may omit the brackets, so that can be
172 written C<\pM> also. Many predefined properties are available, such
173 as C<\p{Mirrored}> and C<\p{Tibetan}>.
175 The official Unicode script and block names have spaces and dashes as
176 separators, but for convenience you can have dashes, spaces, and underbars
177 at every word division, and you need not care about correct casing. It is
178 recommended, however, that for consistency you use the following naming:
179 the official Unicode script, block, or property name (see below for the
180 additional rules that apply to block names), with whitespace and dashes
181 removed, and the words "uppercase-first-lowercase-rest". That is, "Latin-1
182 Supplement" becomes "Latin1Supplement".
184 You can also negate both C<\p{}> and C<\P{}> by introducing a caret
185 (^) between the first curly and the property name: C<\p{^Tamil}> is
186 equal to C<\P{Tamil}>.
188 Here are the basic Unicode General Category properties, followed by their
189 long form (you can use either, e.g. C<\p{Lu}> and C<\p{LowercaseLetter}>
212 Pc ConnectorPunctuation
216 Pi InitialPunctuation
217 (may behave like Ps or Pe depending on usage)
219 (may behave like Ps or Pe depending on usage)
231 Zp ParagraphSeparator
236 Cs Surrogate (not usable)
240 The single-letter properties match all characters in any of the
241 two-letter sub-properties starting with the same letter.
242 There's also C<L&> which is an alias for C<Ll>, C<Lu>, and C<Lt>.
244 Because Perl hides the need for the user to understand the internal
245 representation of Unicode characters, it has no need to support the
246 somewhat messy concept of surrogates. Therefore, the C<Cs> property is not
249 Because scripts differ in their directionality (for example Hebrew is
250 written right to left), Unicode supplies these properties:
255 BidiLRE Left-to-Right Embedding
256 BidiLRO Left-to-Right Override
258 BidiAL Right-to-Left Arabic
259 BidiRLE Right-to-Left Embedding
260 BidiRLO Right-to-Left Override
261 BidiPDF Pop Directional Format
262 BidiEN European Number
263 BidiES European Number Separator
264 BidiET European Number Terminator
266 BidiCS Common Number Separator
267 BidiNSM Non-Spacing Mark
268 BidiBN Boundary Neutral
269 BidiB Paragraph Separator
270 BidiS Segment Separator
272 BidiON Other Neutrals
274 For example, C<\p{BidiR}> matches all characters that are normally
275 written right to left.
281 The scripts available via C<\p{...}> and C<\P{...}>, for example
282 C<\p{Latin}> or \p{Cyrillic>, are as follows:
329 There are also extended property classes that supplement the basic
330 properties, defined by the F<PropList> Unicode database:
345 LogicalOrderException
346 NoncharacterCodePoint
348 OtherDefaultIgnorableCodePoint
360 and further derived properties:
362 Alphabetic Lu + Ll + Lt + Lm + Lo + OtherAlphabetic
363 Lowercase Ll + OtherLowercase
364 Uppercase Lu + OtherUppercase
367 ID_Start Lu + Ll + Lt + Lm + Lo + Nl
368 ID_Continue ID_Start + Mn + Mc + Nd + Pc
371 Assigned Any non-Cn character (i.e. synonym for C<\P{Cn}>)
372 Unassigned Synonym for C<\p{Cn}>
373 Common Any character (or unassigned code point)
374 not explicitly assigned to a script
376 For backward compatability, all properties mentioned so far may have C<Is>
377 prepended to their name (e.g. C<\P{IsLu}> is equal to C<\P{Lu}>).
381 In addition to B<scripts>, Unicode also defines B<blocks> of characters.
382 The difference between scripts and blocks is that the scripts concept is
383 closer to natural languages, while the blocks concept is more an artificial
384 grouping based on groups of mostly 256 Unicode characters. For example, the
385 C<Latin> script contains letters from many blocks. On the other hand, the
386 C<Latin> script does not contain all the characters from those blocks. It
387 does not, for example, contain digits because digits are shared across many
388 scripts. Digits and other similar groups, like punctuation, are in a
389 category called C<Common>.
391 For more about scripts, see the UTR #24:
393 http://www.unicode.org/unicode/reports/tr24/
395 For more about blocks, see:
397 http://www.unicode.org/Public/UNIDATA/Blocks.txt
399 Blocks names are given with the C<In> prefix. For example, the
400 Katakana block is referenced via C<\p{InKatakana}>. The C<In>
401 prefix may be omitted if there is no nameing conflict with a script
402 or any other property, but it is recommended that C<In> always be used
405 These block names are supported:
407 InAlphabeticPresentationForms
409 InArabicPresentationFormsA
410 InArabicPresentationFormsB
421 InByzantineMusicalSymbols
423 InCJKCompatibilityForms
424 InCJKCompatibilityIdeographs
425 InCJKCompatibilityIdeographsSupplement
426 InCJKRadicalsSupplement
427 InCJKSymbolsAndPunctuation
428 InCJKUnifiedIdeographs
429 InCJKUnifiedIdeographsExtensionA
430 InCJKUnifiedIdeographsExtensionB
432 InCombiningDiacriticalMarks
433 InCombiningDiacriticalMarksforSymbols
438 InCyrillicSupplementary
442 InEnclosedAlphanumerics
443 InEnclosedCJKLettersAndMonths
453 InHalfwidthAndFullwidthForms
454 InHangulCompatibilityJamo
459 InHighPrivateUseSurrogates
463 InIdeographicDescriptionCharacters
468 InKatakanaPhoneticExtensions
473 InLatinExtendedAdditional
478 InMathematicalAlphanumericSymbols
479 InMathematicalOperators
480 InMiscellaneousMathematicalSymbolsA
481 InMiscellaneousMathematicalSymbolsB
482 InMiscellaneousSymbols
483 InMiscellaneousTechnical
490 InOpticalCharacterRecognition
496 InSpacingModifierLetters
498 InSuperscriptsAndSubscripts
499 InSupplementalArrowsA
500 InSupplementalArrowsB
501 InSupplementalMathematicalOperators
502 InSupplementaryPrivateUseAreaA
503 InSupplementaryPrivateUseAreaB
513 InUnifiedCanadianAboriginalSyllabics
522 The special pattern C<\X> matches any extended Unicode sequence
523 (a "combining character sequence" in Standardese), where the first
524 character is a base character and subsequent characters are mark
525 characters that apply to the base character. It is equivalent to
530 The C<tr///> operator translates characters instead of bytes. Note
531 that the C<tr///CU> functionality has been removed, as the interface
532 was a mistake. For similar functionality see pack('U0', ...) and
537 Case translation operators use the Unicode case translation tables
538 when provided character input. Note that C<uc()> (also known as C<\U>
539 in doublequoted strings) translates to uppercase, while C<ucfirst>
540 (also known as C<\u> in doublequoted strings) translates to titlecase
541 (for languages that make the distinction). Naturally the
542 corresponding backslash sequences have the same semantics.
546 Most operators that deal with positions or lengths in the string will
547 automatically switch to using character positions, including
548 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
549 C<sprintf()>, C<write()>, and C<length()>. Operators that
550 specifically don't switch include C<vec()>, C<pack()>, and
551 C<unpack()>. Operators that really don't care include C<chomp()>, as
552 well as any other operator that treats a string as a bucket of bits,
553 such as C<sort()>, and the operators dealing with filenames.
557 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
558 since they're often used for byte-oriented formats. (Again, think
559 "C<char>" in the C language.) However, there is a new "C<U>" specifier
560 that will convert between Unicode characters and integers.
564 The C<chr()> and C<ord()> functions work on characters. This is like
565 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
566 C<unpack("C")>. In fact, the latter are how you now emulate
567 byte-oriented C<chr()> and C<ord()> for Unicode strings.
568 (Note that this reveals the internal encoding of Unicode strings,
569 which is not something one normally needs to care about at all.)
573 The bit string operators C<& | ^ ~> can operate on character data.
574 However, for backward compatibility reasons (bit string operations
575 when the characters all are less than 256 in ordinal value) one should
576 not mix C<~> (the bit complement) and characters both less than 256 and
577 equal or greater than 256. Most importantly, the DeMorgan's laws
578 (C<~($x|$y) eq ~$x&~$y>, C<~($x&$y) eq ~$x|~$y>) won't hold.
579 Another way to look at this is that the complement cannot return
580 B<both> the 8-bit (byte) wide bit complement B<and> the full character
585 lc(), uc(), lcfirst(), and ucfirst() work for the following cases:
591 the case mapping is from a single Unicode character to another
592 single Unicode character
596 the case mapping is from a single Unicode character to more
597 than one Unicode character
601 What doesn't yet work are the following cases:
607 the "final sigma" (Greek)
611 anything to with locales (Lithuanian, Turkish, Azeri)
615 See the Unicode Technical Report #21, Case Mappings, for more details.
619 And finally, C<scalar reverse()> reverses by character rather than by byte.
623 =head2 Character encodings for input and output
627 =head2 Unicode Regular Expression Support Level
629 The following list of Unicode regular expression support describes
630 feature by feature the Unicode support implemented in Perl as of Perl
631 5.8.0. The "Level N" and the section numbers refer to the Unicode
632 Technical Report 18, "Unicode Regular Expression Guidelines".
638 Level 1 - Basic Unicode Support
640 2.1 Hex Notation - done [1]
641 Named Notation - done [2]
642 2.2 Categories - done [3][4]
643 2.3 Subtraction - MISSING [5][6]
644 2.4 Simple Word Boundaries - done [7]
645 2.5 Simple Loose Matches - done [8]
646 2.6 End of Line - MISSING [9][10]
650 [ 3] . \p{...} \P{...}
651 [ 4] now scripts (see UTR#24 Script Names) in addition to blocks
653 [ 6] can use look-ahead to emulate subtraction (*)
654 [ 7] include Letters in word characters
655 [ 8] note that perl does Full casefolding in matching, not Simple:
656 for example U+1F88 is equivalent with U+1F000 U+03B9,
657 not with 1F80. This difference matters for certain Greek
658 capital letters with certain modifiers: the Full casefolding
659 decomposes the letter, while the Simple casefolding would map
660 it to a single character.
661 [ 9] see UTR#13 Unicode Newline Guidelines
662 [10] should do ^ and $ also on \x{85}, \x{2028} and \x{2029})
663 (should also affect <>, $., and script line numbers)
664 (the \x{85}, \x{2028} and \x{2029} do match \s)
666 (*) You can mimic class subtraction using lookahead.
667 For example, what TR18 might write as
669 [{Greek}-[{UNASSIGNED}]]
671 in Perl can be written as:
673 (?!\p{Unassigned})\p{InGreekAndCoptic}
674 (?=\p{Assigned})\p{InGreekAndCoptic}
676 But in this particular example, you probably really want
680 which will match assigned characters known to be part of the Greek script.
684 Level 2 - Extended Unicode Support
686 3.1 Surrogates - MISSING
687 3.2 Canonical Equivalents - MISSING [11][12]
688 3.3 Locale-Independent Graphemes - MISSING [13]
689 3.4 Locale-Independent Words - MISSING [14]
690 3.5 Locale-Independent Loose Matches - MISSING [15]
692 [11] see UTR#15 Unicode Normalization
693 [12] have Unicode::Normalize but not integrated to regexes
694 [13] have \X but at this level . should equal that
695 [14] need three classes, not just \w and \W
696 [15] see UTR#21 Case Mappings
700 Level 3 - Locale-Sensitive Support
702 4.1 Locale-Dependent Categories - MISSING
703 4.2 Locale-Dependent Graphemes - MISSING [16][17]
704 4.3 Locale-Dependent Words - MISSING
705 4.4 Locale-Dependent Loose Matches - MISSING
706 4.5 Locale-Dependent Ranges - MISSING
708 [16] see UTR#10 Unicode Collation Algorithms
709 [17] have Unicode::Collate but not integrated to regexes
713 =head2 Unicode Encodings
715 Unicode characters are assigned to I<code points> which are abstract
716 numbers. To use these numbers various encodings are needed.
724 UTF-8 is a variable-length (1 to 6 bytes, current character allocations
725 require 4 bytes), byteorder independent encoding. For ASCII, UTF-8 is
726 transparent (and we really do mean 7-bit ASCII, not another 8-bit encoding).
728 The following table is from Unicode 3.2.
730 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
732 U+0000..U+007F 00..7F
733 U+0080..U+07FF C2..DF 80..BF
734 U+0800..U+0FFF E0 A0..BF 80..BF
735 U+1000..U+CFFF E1..EC 80..BF 80..BF
736 U+D000..U+D7FF ED 80..9F 80..BF
737 U+D800..U+DFFF ******* ill-formed *******
738 U+E000..U+FFFF EE..EF 80..BF 80..BF
739 U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
740 U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
741 U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
743 Note the A0..BF in U+0800..U+0FFF, the 80..9F in U+D000...U+D7FF,
744 the 90..BF in U+10000..U+3FFFF, and the 80...8F in U+100000..U+10FFFF.
745 The "gaps" are caused by legal UTF-8 avoiding non-shortest encodings:
746 it is technically possible to UTF-8-encode a single code point in different
747 ways, but that is explicitly forbidden, and the shortest possible encoding
748 should always be used (and that is what Perl does).
750 Or, another way to look at it, as bits:
752 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
755 00000bbbbbaaaaaa 110bbbbb 10aaaaaa
756 ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
757 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa
759 As you can see, the continuation bytes all begin with C<10>, and the
760 leading bits of the start byte tell how many bytes the are in the
767 Like UTF-8, but EBCDIC-safe, as UTF-8 is ASCII-safe.
771 UTF-16, UTF-16BE, UTF16-LE, Surrogates, and BOMs (Byte Order Marks)
773 (The followings items are mostly for reference, Perl doesn't
774 use them internally.)
776 UTF-16 is a 2 or 4 byte encoding. The Unicode code points
777 0x0000..0xFFFF are stored in two 16-bit units, and the code points
778 0x010000..0x10FFFF in two 16-bit units. The latter case is
779 using I<surrogates>, the first 16-bit unit being the I<high
780 surrogate>, and the second being the I<low surrogate>.
782 Surrogates are code points set aside to encode the 0x01000..0x10FFFF
783 range of Unicode code points in pairs of 16-bit units. The I<high
784 surrogates> are the range 0xD800..0xDBFF, and the I<low surrogates>
785 are the range 0xDC00..0xDFFFF. The surrogate encoding is
787 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
788 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
792 $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
794 If you try to generate surrogates (for example by using chr()), you
795 will get a warning if warnings are turned on (C<-w> or C<use
796 warnings;>) because those code points are not valid for a Unicode
799 Because of the 16-bitness, UTF-16 is byteorder dependent. UTF-16
800 itself can be used for in-memory computations, but if storage or
801 transfer is required, either UTF-16BE (Big Endian) or UTF-16LE
802 (Little Endian) must be chosen.
804 This introduces another problem: what if you just know that your data
805 is UTF-16, but you don't know which endianness? Byte Order Marks
806 (BOMs) are a solution to this. A special character has been reserved
807 in Unicode to function as a byte order marker: the character with the
808 code point 0xFEFF is the BOM.
810 The trick is that if you read a BOM, you will know the byte order,
811 since if it was written on a big endian platform, you will read the
812 bytes 0xFE 0xFF, but if it was written on a little endian platform,
813 you will read the bytes 0xFF 0xFE. (And if the originating platform
814 was writing in UTF-8, you will read the bytes 0xEF 0xBB 0xBF.)
816 The way this trick works is that the character with the code point
817 0xFFFE is guaranteed not to be a valid Unicode character, so the
818 sequence of bytes 0xFF 0xFE is unambiguously "BOM, represented in
819 little-endian format" and cannot be "0xFFFE, represented in big-endian
824 UTF-32, UTF-32BE, UTF32-LE
826 The UTF-32 family is pretty much like the UTF-16 family, expect that
827 the units are 32-bit, and therefore the surrogate scheme is not
828 needed. The BOM signatures will be 0x00 0x00 0xFE 0xFF for BE and
829 0xFF 0xFE 0x00 0x00 for LE.
835 Encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit
836 encoding, UCS-4 is a 32-bit encoding. Unlike UTF-16, UCS-2
837 is not extensible beyond 0xFFFF, because it does not use surrogates.
843 A seven-bit safe (non-eight-bit) encoding, useful if the
844 transport/storage is not eight-bit safe. Defined by RFC 2152.
848 =head2 Security Implications of Malformed UTF-8
850 Unfortunately, the specification of UTF-8 leaves some room for
851 interpretation of how many bytes of encoded output one should generate
852 from one input Unicode character. Strictly speaking, one is supposed
853 to always generate the shortest possible sequence of UTF-8 bytes,
854 because otherwise there is potential for input buffer overflow at
855 the receiving end of a UTF-8 connection. Perl always generates the
856 shortest length UTF-8, and with warnings on (C<-w> or C<use
857 warnings;>) Perl will warn about non-shortest length UTF-8 (and other
858 malformations, too, such as the surrogates, which are not real
859 Unicode code points.)
861 =head2 Unicode in Perl on EBCDIC
863 The way Unicode is handled on EBCDIC platforms is still rather
864 experimental. On such a platform, references to UTF-8 encoding in this
865 document and elsewhere should be read as meaning UTF-EBCDIC as
866 specified in Unicode Technical Report 16 unless ASCII vs EBCDIC issues
867 are specifically discussed. There is no C<utfebcdic> pragma or
868 ":utfebcdic" layer, rather, "utf8" and ":utf8" are re-used to mean
869 the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic>
870 for more discussion of the issues.
874 Usually locale settings and Unicode do not affect each other, but
875 there are a couple of exceptions:
881 If your locale environment variables (LANGUAGE, LC_ALL, LC_CTYPE, LANG)
882 contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
883 the default encoding of your STDIN, STDOUT, and STDERR, and of
884 B<any subsequent file open>, is UTF-8.
888 Perl tries really hard to work both with Unicode and the old byte
889 oriented world: most often this is nice, but sometimes this causes
894 =head2 Using Unicode in XS
896 If you want to handle Perl Unicode in XS extensions, you may find
897 the following C APIs useful (see perlapi for details):
903 DO_UTF8(sv) returns true if the UTF8 flag is on and the bytes pragma
904 is not in effect. SvUTF8(sv) returns true is the UTF8 flag is on, the
905 bytes pragma is ignored. The UTF8 flag being on does B<not> mean that
906 there are any characters of code points greater than 255 (or 127) in
907 the scalar, or that there even are any characters in the scalar.
908 What the UTF8 flag means is that the sequence of octets in the
909 representation of the scalar is the sequence of UTF-8 encoded
910 code points of the characters of a string. The UTF8 flag being
911 off means that each octet in this representation encodes a single
912 character with codepoint 0..255 within the string. Perl's Unicode
913 model is not to use UTF-8 until it's really necessary.
917 uvuni_to_utf8(buf, chr) writes a Unicode character code point into a
918 buffer encoding the code point as UTF-8, and returns a pointer
919 pointing after the UTF-8 bytes.
923 utf8_to_uvuni(buf, lenp) reads UTF-8 encoded bytes from a buffer and
924 returns the Unicode character code point (and optionally the length of
925 the UTF-8 byte sequence).
929 utf8_length(start, end) returns the length of the UTF-8 encoded buffer
930 in characters. sv_len_utf8(sv) returns the length of the UTF-8 encoded
935 sv_utf8_upgrade(sv) converts the string of the scalar to its UTF-8
936 encoded form. sv_utf8_downgrade(sv) does the opposite (if possible).
937 sv_utf8_encode(sv) is like sv_utf8_upgrade but the UTF8 flag does not
938 get turned on. sv_utf8_decode() does the opposite of sv_utf8_encode().
939 Note that none of these are to be used as general purpose encoding/decoding
940 interfaces: use Encode for that. sv_utf8_upgrade() is affected by the
941 encoding pragma, but sv_utf8_downgrade() is not (since the encoding
942 pragma is designed to be a one-way street).
946 is_utf8_char(s) returns true if the pointer points to a valid UTF-8
951 is_utf8_string(buf, len) returns true if the len bytes of the buffer
956 UTF8SKIP(buf) will return the number of bytes in the UTF-8 encoded
957 character in the buffer. UNISKIP(chr) will return the number of bytes
958 required to UTF-8-encode the Unicode character code point. UTF8SKIP()
959 is useful for example for iterating over the characters of a UTF-8
960 encoded buffer; UNISKIP() is useful for example in computing
961 the size required for a UTF-8 encoded buffer.
965 utf8_distance(a, b) will tell the distance in characters between the
966 two pointers pointing to the same UTF-8 encoded buffer.
970 utf8_hop(s, off) will return a pointer to an UTF-8 encoded buffer that
971 is C<off> (positive or negative) Unicode characters displaced from the
972 UTF-8 buffer C<s>. Be careful not to overstep the buffer: utf8_hop()
973 will merrily run off the end or the beginning if told to do so.
977 pv_uni_display(dsv, spv, len, pvlim, flags) and sv_uni_display(dsv,
978 ssv, pvlim, flags) are useful for debug output of Unicode strings and
979 scalars. By default they are useful only for debug: they display
980 B<all> characters as hexadecimal code points, but with the flags
981 UNI_DISPLAY_ISPRINT and UNI_DISPLAY_BACKSLASH you can make the output
986 ibcmp_utf8(s1, pe1, u1, l1, u1, s2, pe2, l2, u2) can be used to
987 compare two strings case-insensitively in Unicode.
988 (For case-sensitive comparisons you can just use memEQ() and memNE()
993 For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h>
994 in the Perl source code distribution.
998 Use of locales with Unicode data may lead to odd results. Currently
999 there is some attempt to apply 8-bit locale info to characters in the
1000 range 0..255, but this is demonstrably incorrect for locales that use
1001 characters above that range when mapped into Unicode. It will also
1002 tend to run slower. Use of locales with Unicode is discouraged.
1004 Some functions are slower when working on UTF-8 encoded strings than
1005 on byte encoded strings. All functions that need to hop over
1006 characters such as length(), substr() or index() can work B<much>
1007 faster when the underlying data are byte-encoded. Witness the
1008 following benchmark:
1014 our $u = our $b = "x" x $l;
1015 substr($u,0,1) = "\x{100}";
1017 LENGTH_B => q{ length($b) },
1018 LENGTH_U => q{ length($u) },
1019 SUBSTR_B => q{ substr($b, $l/4, $l/2) },
1020 SUBSTR_U => q{ substr($u, $l/4, $l/2) },
1023 Benchmark: running LENGTH_B, LENGTH_U, SUBSTR_B, SUBSTR_U for at least 2 CPU seconds...
1024 LENGTH_B: 2 wallclock secs ( 2.36 usr + 0.00 sys = 2.36 CPU) @ 5649983.05/s (n=13333960)
1025 LENGTH_U: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 12155.45/s (n=25648)
1026 SUBSTR_B: 3 wallclock secs ( 2.16 usr + 0.00 sys = 2.16 CPU) @ 374480.09/s (n=808877)
1027 SUBSTR_U: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 6791.00/s (n=14329)
1029 The numbers show an incredible slowness on long UTF-8 strings and you
1030 should carefully avoid to use these functions within tight loops. For
1031 example if you want to iterate over characters, it is infinitely
1032 better to split into an array than to use substr, as the following
1039 our $u = our $b = "x" x $l;
1040 substr($u,0,1) = "\x{100}";
1042 SPLIT_B => q{ for my $c (split //, $b){} },
1043 SPLIT_U => q{ for my $c (split //, $u){} },
1044 SUBSTR_B => q{ for my $i (0..length($b)-1){my $c = substr($b,$i,1);} },
1045 SUBSTR_U => q{ for my $i (0..length($u)-1){my $c = substr($u,$i,1);} },
1048 Benchmark: running SPLIT_B, SPLIT_U, SUBSTR_B, SUBSTR_U for at least 5 CPU seconds...
1049 SPLIT_B: 6 wallclock secs ( 5.29 usr + 0.00 sys = 5.29 CPU) @ 56.14/s (n=297)
1050 SPLIT_U: 5 wallclock secs ( 5.17 usr + 0.01 sys = 5.18 CPU) @ 55.21/s (n=286)
1051 SUBSTR_B: 5 wallclock secs ( 5.34 usr + 0.00 sys = 5.34 CPU) @ 123.22/s (n=658)
1052 SUBSTR_U: 7 wallclock secs ( 6.20 usr + 0.00 sys = 6.20 CPU) @ 0.81/s (n=5)
1054 You see, the algorithm based on substr() was faster with byte encoded
1055 data but it is pathologically slow with UTF-8 data.
1059 L<perluniintro>, L<encoding>, L<Encode>, L<open>, L<utf8>, L<bytes>,
1060 L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">