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 To mark the Perl source itself as being in 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 switch to the Unicode
30 character scheme when presented with Unicode data, or a traditional
31 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, this pragma must be explicitly used to
36 enable recognition of UTF-8 in the Perl scripts themselves on ASCII
37 based machines, or to recognize UTF-EBCDIC on EBCDIC based machines.
38 B<NOTE: this should be the only place where 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 can be expected to work with
52 characters rather than bytes, in general.
54 However, as strictly 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 is characters, Perl now 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, but only as long as
64 none of the program's inputs are 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. Note that this is
72 currently only implemented on Windows since other platforms lack an
73 API standard on this area.
75 Regardless of the above, the C<bytes> pragma can always be used to
76 force byte 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 until a future version of Perl
81 in which character semantics will become the default. This pragma may
82 then become a no-op. See L<utf8>.
84 Unless mentioned otherwise, Perl operators will use character semantics
85 when they are dealing with Unicode data, and byte semantics otherwise.
86 Thus, character semantics for these operations apply transparently; if
87 the input data came from a Unicode source (for example, by adding a
88 character encoding discipline to the filehandle whence it came, or a
89 literal Unicode string constant in the program), character semantics
90 apply; otherwise, byte semantics are in effect. To force byte semantics
91 on Unicode data, the C<bytes> pragma should be used.
93 Notice that if you concatenate strings with byte semantics and strings
94 with Unicode character data, the bytes will by default be upgraded
95 I<as if they were ISO 8859-1 (Latin-1)> (or if in EBCDIC, after a
96 translation to ISO 8859-1). This is done without regard to the
97 system's native 8-bit encoding, so to change this for systems with
98 non-Latin-1 (or non-EBCDIC) native encodings, use the C<encoding>
99 pragma, see L<encoding>.
101 Under character semantics, many operations that formerly operated on
102 bytes change to operating 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 to longer sequences of bytes internally, but
105 this is just an internal detail which is hidden at the Perl level.
106 See L<perluniintro> for more on this.
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 are recognized
122 as such (and converted to Perl's internal representation) only if the
123 appropriate L<encoding> is specified.
125 You can also get Unicode characters into a string by using the C<\x{...}>
126 notation, putting the Unicode code for the desired character, in
127 hexadecimal, into the curlies. For instance, a smiley face is C<\x{263A}>.
128 This works only for characters with a code 0x100 and above.
132 use charnames ':full';
134 you can use the C<\N{...}> notation, putting the official Unicode character
135 name within the curlies. For example, C<\N{WHITE SMILING FACE}>.
136 This works for all characters that have names.
140 If an appropriate L<encoding> is specified, identifiers within the
141 Perl script may contain Unicode alphanumeric characters, including
142 ideographs. (You are currently on your own when it comes to using the
143 canonical forms of characters--Perl doesn't (yet) attempt to
144 canonicalize variable names for you.)
148 Regular expressions match characters instead of bytes. For instance,
149 "." matches a character instead of a byte. (However, the C<\C> pattern
150 is provided to force a match a single byte ("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. So 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 new C<\p{}> (matches property) and C<\P{}>
163 (doesn't match property) constructs. For instance, C<\p{Lu}> matches any
164 character with the Unicode "Lu" (Letter, uppercase) property, while
165 C<\p{M}> matches any character with a "M" (mark -- accents and such)
166 property. Single letter properties may omit the brackets, so that can be
167 written C<\pM> also. Many predefined properties are available, such
168 as C<\p{Mirrored}> and C<\p{Tibetan}>.
170 The official Unicode script and block names have spaces and dashes as
171 separators, but for convenience you can have dashes, spaces, and underbars
172 at every word division, and you need not care about correct casing. It is
173 recommended, however, that for consistency you use the following naming:
174 the official Unicode script, block, or property name (see below for the
175 additional rules that apply to block names), with whitespace and dashes
176 removed, and the words "uppercase-first-lowercase-rest". That is, "Latin-1
177 Supplement" becomes "Latin1Supplement".
179 You can also negate both C<\p{}> and C<\P{}> by introducing a caret
180 (^) between the first curly and the property name: C<\p{^Tamil}> is
181 equal to C<\P{Tamil}>.
183 Here are the basic Unicode General Category properties, followed by their
184 long form (you can use either, e.g. C<\p{Lu}> and C<\p{LowercaseLetter}>
207 Pc ConnectorPunctuation
211 Pi InitialPunctuation
212 (may behave like Ps or Pe depending on usage)
214 (may behave like Ps or Pe depending on usage)
226 Zp ParagraphSeparator
231 Cs Surrogate (not usable)
235 The single-letter properties match all characters in any of the
236 two-letter sub-properties starting with the same letter.
237 There's also C<L&> which is an alias for C<Ll>, C<Lu>, and C<Lt>.
239 Because Perl hides the need for the user to understand the internal
240 representation of Unicode characters, it has no need to support the
241 somewhat messy concept of surrogates. Therefore, the C<Cs> property is not
244 Because scripts differ in their directionality (for example Hebrew is
245 written right to left), Unicode supplies these properties:
250 BidiLRE Left-to-Right Embedding
251 BidiLRO Left-to-Right Override
253 BidiAL Right-to-Left Arabic
254 BidiRLE Right-to-Left Embedding
255 BidiRLO Right-to-Left Override
256 BidiPDF Pop Directional Format
257 BidiEN European Number
258 BidiES European Number Separator
259 BidiET European Number Terminator
261 BidiCS Common Number Separator
262 BidiNSM Non-Spacing Mark
263 BidiBN Boundary Neutral
264 BidiB Paragraph Separator
265 BidiS Segment Separator
267 BidiON Other Neutrals
269 For example, C<\p{BidiR}> matches all characters that are normally
270 written right to left.
276 The scripts available via C<\p{...}> and C<\P{...}>, for example
277 C<\p{Latin}> or \p{Cyrillic>, are as follows:
320 There are also extended property classes that supplement the basic
321 properties, defined by the F<PropList> Unicode database:
332 NoncharacterCodePoint
340 and further derived properties:
342 Alphabetic Lu + Ll + Lt + Lm + Lo + OtherAlphabetic
343 Lowercase Ll + OtherLowercase
344 Uppercase Lu + OtherUppercase
347 ID_Start Lu + Ll + Lt + Lm + Lo + Nl
348 ID_Continue ID_Start + Mn + Mc + Nd + Pc
351 Assigned Any non-Cn character (i.e. synonym for C<\P{Cn}>)
352 Unassigned Synonym for C<\p{Cn}>
353 Common Any character (or unassigned code point)
354 not explicitly assigned to a script
356 For backward compatability, all properties mentioned so far may have C<Is>
357 prepended to their name (e.g. C<\P{IsLu}> is equal to C<\P{Lu}>).
361 In addition to B<scripts>, Unicode also defines B<blocks> of characters.
362 The difference between scripts and blocks is that the scripts concept is
363 closer to natural languages, while the blocks concept is more an artificial
364 grouping based on groups of mostly 256 Unicode characters. For example, the
365 C<Latin> script contains letters from many blocks. On the other hand, the
366 C<Latin> script does not contain all the characters from those blocks. It
367 does not, for example, contain digits because digits are shared across many
368 scripts. Digits and other similar groups, like punctuation, are in a
369 category called C<Common>.
371 For more about scripts, see the UTR #24:
373 http://www.unicode.org/unicode/reports/tr24/
375 For more about blocks, see:
377 http://www.unicode.org/Public/UNIDATA/Blocks.txt
379 Blocks names are given with the C<In> prefix. For example, the
380 Katakana block is referenced via C<\p{InKatakana}>. The C<In>
381 prefix may be omitted if there is no nameing conflict with a script
382 or any other property, but it is recommended that C<In> always be used
385 These block names are supported:
387 InAlphabeticPresentationForms
389 InArabicPresentationFormsA
390 InArabicPresentationFormsB
400 InByzantineMusicalSymbols
402 InCJKCompatibilityForms
403 InCJKCompatibilityIdeographs
404 InCJKCompatibilityIdeographsSupplement
405 InCJKRadicalsSupplement
406 InCJKSymbolsAndPunctuation
407 InCJKUnifiedIdeographs
408 InCJKUnifiedIdeographsExtensionA
409 InCJKUnifiedIdeographsExtensionB
411 InCombiningDiacriticalMarks
413 InCombiningMarksForSymbols
420 InEnclosedAlphanumerics
421 InEnclosedCJKLettersAndMonths
431 InHalfwidthAndFullwidthForms
432 InHangulCompatibilityJamo
436 InHighPrivateUseSurrogates
440 InIdeographicDescriptionCharacters
448 InLatinExtendedAdditional
454 InMathematicalAlphanumericSymbols
455 InMathematicalOperators
456 InMiscellaneousSymbols
457 InMiscellaneousTechnical
464 InOpticalCharacterRecognition
470 InSpacingModifierLetters
472 InSuperscriptsAndSubscripts
480 InUnifiedCanadianAboriginalSyllabics
488 The special pattern C<\X> matches any extended Unicode sequence
489 (a "combining character sequence" in Standardese), where the first
490 character is a base character and subsequent characters are mark
491 characters that apply to the base character. It is equivalent to
496 The C<tr///> operator translates characters instead of bytes. Note
497 that the C<tr///CU> functionality has been removed, as the interface
498 was a mistake. For similar functionality see pack('U0', ...) and
503 Case translation operators use the Unicode case translation tables
504 when provided character input. Note that C<uc()> (also known as C<\U>
505 in doublequoted strings) translates to uppercase, while C<ucfirst>
506 (also known as C<\u> in doublequoted strings) translates to titlecase
507 (for languages that make the distinction). Naturally the
508 corresponding backslash sequences have the same semantics.
512 Most operators that deal with positions or lengths in the string will
513 automatically switch to using character positions, including
514 C<chop()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
515 C<sprintf()>, C<write()>, and C<length()>. Operators that
516 specifically don't switch include C<vec()>, C<pack()>, and
517 C<unpack()>. Operators that really don't care include C<chomp()>, as
518 well as any other operator that treats a string as a bucket of bits,
519 such as C<sort()>, and the operators dealing with filenames.
523 The C<pack()>/C<unpack()> letters "C<c>" and "C<C>" do I<not> change,
524 since they're often used for byte-oriented formats. (Again, think
525 "C<char>" in the C language.) However, there is a new "C<U>" specifier
526 that will convert between Unicode characters and integers.
530 The C<chr()> and C<ord()> functions work on characters. This is like
531 C<pack("U")> and C<unpack("U")>, not like C<pack("C")> and
532 C<unpack("C")>. In fact, the latter are how you now emulate
533 byte-oriented C<chr()> and C<ord()> for Unicode strings.
534 (Note that this reveals the internal encoding of Unicode strings,
535 which is not something one normally needs to care about at all.)
539 The bit string operators C<& | ^ ~> can operate on character data.
540 However, for backward compatibility reasons (bit string operations
541 when the characters all are less than 256 in ordinal value) one should
542 not mix C<~> (the bit complement) and characters both less than 256 and
543 equal or greater than 256. Most importantly, the DeMorgan's laws
544 (C<~($x|$y) eq ~$x&~$y>, C<~($x&$y) eq ~$x|~$y>) won't hold.
545 Another way to look at this is that the complement cannot return
546 B<both> the 8-bit (byte) wide bit complement B<and> the full character
551 lc(), uc(), lcfirst(), and ucfirst() work for the following cases:
557 the case mapping is from a single Unicode character to another
558 single Unicode character
562 the case mapping is from a single Unicode character to more
563 than one Unicode character
567 What doesn't yet work are the following cases:
573 the "final sigma" (Greek)
577 anything to with locales (Lithuanian, Turkish, Azeri)
581 See the Unicode Technical Report #21, Case Mappings, for more details.
585 And finally, C<scalar reverse()> reverses by character rather than by byte.
589 =head2 Character encodings for input and output
593 =head2 Unicode Regular Expression Support Level
595 The following list of Unicode regular expression support describes
596 feature by feature the Unicode support implemented in Perl as of Perl
597 5.8.0. The "Level N" and the section numbers refer to the Unicode
598 Technical Report 18, "Unicode Regular Expression Guidelines".
604 Level 1 - Basic Unicode Support
606 2.1 Hex Notation - done [1]
607 Named Notation - done [2]
608 2.2 Categories - done [3][4]
609 2.3 Subtraction - MISSING [5][6]
610 2.4 Simple Word Boundaries - done [7]
611 2.5 Simple Loose Matches - done [8]
612 2.6 End of Line - MISSING [9][10]
616 [ 3] . \p{...} \P{...}
617 [ 4] now scripts (see UTR#24 Script Names) in addition to blocks
619 [ 6] can use look-ahead to emulate subtraction (*)
620 [ 7] include Letters in word characters
621 [ 8] note that perl does Full casefolding in matching, not Simple:
622 for example U+1F88 is equivalent with U+1F000 U+03B9,
623 not with 1F80. This difference matters for certain Greek
624 capital letters with certain modifiers: the Full casefolding
625 decomposes the letter, while the Simple casefolding would map
626 it to a single character.
627 [ 9] see UTR#13 Unicode Newline Guidelines
628 [10] should do ^ and $ also on \x{85}, \x{2028} and \x{2029})
629 (should also affect <>, $., and script line numbers)
630 (the \x{85}, \x{2028} and \x{2029} do match \s)
632 (*) You can mimic class subtraction using lookahead.
633 For example, what TR18 might write as
635 [{Greek}-[{UNASSIGNED}]]
637 in Perl can be written as:
639 (?!\p{Unassigned})\p{InGreek}
640 (?=\p{Assigned})\p{InGreek}
642 But in this particular example, you probably really want
646 which will match assigned characters known to be part of the Greek script.
650 Level 2 - Extended Unicode Support
652 3.1 Surrogates - MISSING
653 3.2 Canonical Equivalents - MISSING [11][12]
654 3.3 Locale-Independent Graphemes - MISSING [13]
655 3.4 Locale-Independent Words - MISSING [14]
656 3.5 Locale-Independent Loose Matches - MISSING [15]
658 [11] see UTR#15 Unicode Normalization
659 [12] have Unicode::Normalize but not integrated to regexes
660 [13] have \X but at this level . should equal that
661 [14] need three classes, not just \w and \W
662 [15] see UTR#21 Case Mappings
666 Level 3 - Locale-Sensitive Support
668 4.1 Locale-Dependent Categories - MISSING
669 4.2 Locale-Dependent Graphemes - MISSING [16][17]
670 4.3 Locale-Dependent Words - MISSING
671 4.4 Locale-Dependent Loose Matches - MISSING
672 4.5 Locale-Dependent Ranges - MISSING
674 [16] see UTR#10 Unicode Collation Algorithms
675 [17] have Unicode::Collate but not integrated to regexes
679 =head2 Unicode Encodings
681 Unicode characters are assigned to I<code points> which are abstract
682 numbers. To use these numbers various encodings are needed.
690 UTF-8 is a variable-length (1 to 6 bytes, current character allocations
691 require 4 bytes), byteorder independent encoding. For ASCII, UTF-8 is
692 transparent (and we really do mean 7-bit ASCII, not another 8-bit encoding).
694 The following table is from Unicode 3.2.
696 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
698 U+0000..U+007F 00..7F
699 U+0080..U+07FF C2..DF 80..BF
700 U+0800..U+0FFF E0 A0..BF 80..BF
701 U+1000..U+CFFF E1..EC 80..BF 80..BF
702 U+D000..U+D7FF ED 80..9F 80..BF
703 U+D800..U+DFFF ******* ill-formed *******
704 U+E000..U+FFFF EE..EF 80..BF 80..BF
705 U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
706 U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
707 U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
709 Note the A0..BF in U+0800..U+0FFF, the 80..9F in U+D000...U+D7FF,
710 the 90..BF in U+10000..U+3FFFF, and the 80...8F in U+100000..U+10FFFF.
711 Or, another way to look at it, as bits:
713 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
716 00000bbbbbaaaaaa 110bbbbb 10aaaaaa
717 ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
718 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa
720 As you can see, the continuation bytes all begin with C<10>, and the
721 leading bits of the start byte tell how many bytes the are in the
728 Like UTF-8, but EBCDIC-safe, as UTF-8 is ASCII-safe.
732 UTF-16, UTF-16BE, UTF16-LE, Surrogates, and BOMs (Byte Order Marks)
734 (The followings items are mostly for reference, Perl doesn't
735 use them internally.)
737 UTF-16 is a 2 or 4 byte encoding. The Unicode code points
738 0x0000..0xFFFF are stored in two 16-bit units, and the code points
739 0x010000..0x10FFFF in two 16-bit units. The latter case is
740 using I<surrogates>, the first 16-bit unit being the I<high
741 surrogate>, and the second being the I<low surrogate>.
743 Surrogates are code points set aside to encode the 0x01000..0x10FFFF
744 range of Unicode code points in pairs of 16-bit units. The I<high
745 surrogates> are the range 0xD800..0xDBFF, and the I<low surrogates>
746 are the range 0xDC00..0xDFFFF. The surrogate encoding is
748 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
749 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
753 $uni = 0x10000 + ($hi - 0xD8000) * 0x400 + ($lo - 0xDC00);
755 If you try to generate surrogates (for example by using chr()), you
756 will get a warning if warnings are turned on (C<-w> or C<use
757 warnings;>) because those code points are not valid for a Unicode
760 Because of the 16-bitness, UTF-16 is byteorder dependent. UTF-16
761 itself can be used for in-memory computations, but if storage or
762 transfer is required, either UTF-16BE (Big Endian) or UTF-16LE
763 (Little Endian) must be chosen.
765 This introduces another problem: what if you just know that your data
766 is UTF-16, but you don't know which endianness? Byte Order Marks
767 (BOMs) are a solution to this. A special character has been reserved
768 in Unicode to function as a byte order marker: the character with the
769 code point 0xFEFF is the BOM.
771 The trick is that if you read a BOM, you will know the byte order,
772 since if it was written on a big endian platform, you will read the
773 bytes 0xFE 0xFF, but if it was written on a little endian platform,
774 you will read the bytes 0xFF 0xFE. (And if the originating platform
775 was writing in UTF-8, you will read the bytes 0xEF 0xBB 0xBF.)
777 The way this trick works is that the character with the code point
778 0xFFFE is guaranteed not to be a valid Unicode character, so the
779 sequence of bytes 0xFF 0xFE is unambiguously "BOM, represented in
780 little-endian format" and cannot be "0xFFFE, represented in big-endian
785 UTF-32, UTF-32BE, UTF32-LE
787 The UTF-32 family is pretty much like the UTF-16 family, expect that
788 the units are 32-bit, and therefore the surrogate scheme is not
789 needed. The BOM signatures will be 0x00 0x00 0xFE 0xFF for BE and
790 0xFF 0xFE 0x00 0x00 for LE.
796 Encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit
797 encoding, UCS-4 is a 32-bit encoding. Unlike UTF-16, UCS-2
798 is not extensible beyond 0xFFFF, because it does not use surrogates.
804 A seven-bit safe (non-eight-bit) encoding, useful if the
805 transport/storage is not eight-bit safe. Defined by RFC 2152.
809 =head2 Security Implications of Malformed UTF-8
811 Unfortunately, the specification of UTF-8 leaves some room for
812 interpretation of how many bytes of encoded output one should generate
813 from one input Unicode character. Strictly speaking, one is supposed
814 to always generate the shortest possible sequence of UTF-8 bytes,
815 because otherwise there is potential for input buffer overflow at
816 the receiving end of a UTF-8 connection. Perl always generates the
817 shortest length UTF-8, and with warnings on (C<-w> or C<use
818 warnings;>) Perl will warn about non-shortest length UTF-8 (and other
819 malformations, too, such as the surrogates, which are not real
820 Unicode code points.)
822 =head2 Unicode in Perl on EBCDIC
824 The way Unicode is handled on EBCDIC platforms is still rather
825 experimental. On such a platform, references to UTF-8 encoding in this
826 document and elsewhere should be read as meaning UTF-EBCDIC as
827 specified in Unicode Technical Report 16 unless ASCII vs EBCDIC issues
828 are specifically discussed. There is no C<utfebcdic> pragma or
829 ":utfebcdic" layer, rather, "utf8" and ":utf8" are re-used to mean
830 the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic>
831 for more discussion of the issues.
835 Usually locale settings and Unicode do not affect each other, but
836 there are a couple of exceptions:
842 If your locale environment variables (LANGUAGE, LC_ALL, LC_CTYPE, LANG)
843 contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
844 the default encoding of your STDIN, STDOUT, and STDERR, and of
845 B<any subsequent file open>, is UTF-8.
849 Perl tries really hard to work both with Unicode and the old byte
850 oriented world: most often this is nice, but sometimes this causes
855 =head2 Using Unicode in XS
857 If you want to handle Perl Unicode in XS extensions, you may find
858 the following C APIs useful (see perlapi for details):
864 DO_UTF8(sv) returns true if the UTF8 flag is on and the bytes pragma
865 is not in effect. SvUTF8(sv) returns true is the UTF8 flag is on, the
866 bytes pragma is ignored. The UTF8 flag being on does B<not> mean that
867 there are any characters of code points greater than 255 (or 127) in
868 the scalar, or that there even are any characters in the scalar.
869 What the UTF8 flag means is that the sequence of octets in the
870 representation of the scalar is the sequence of UTF-8 encoded
871 code points of the characters of a string. The UTF8 flag being
872 off means that each octet in this representation encodes a single
873 character with codepoint 0..255 within the string. Perl's Unicode
874 model is not to use UTF-8 until it's really necessary.
878 uvuni_to_utf8(buf, chr) writes a Unicode character code point into a
879 buffer encoding the code point as UTF-8, and returns a pointer
880 pointing after the UTF-8 bytes.
884 utf8_to_uvuni(buf, lenp) reads UTF-8 encoded bytes from a buffer and
885 returns the Unicode character code point (and optionally the length of
886 the UTF-8 byte sequence).
890 utf8_length(start, end) returns the length of the UTF-8 encoded buffer
891 in characters. sv_len_utf8(sv) returns the length of the UTF-8 encoded
896 sv_utf8_upgrade(sv) converts the string of the scalar to its UTF-8
897 encoded form. sv_utf8_downgrade(sv) does the opposite (if possible).
898 sv_utf8_encode(sv) is like sv_utf8_upgrade but the UTF8 flag does not
899 get turned on. sv_utf8_decode() does the opposite of sv_utf8_encode().
900 Note that none of these are to be used as general purpose encoding/decoding
901 interfaces: use Encode for that. sv_utf8_upgrade() is affected by the
902 encoding pragma, but sv_utf8_downgrade() is not (since the encoding
903 pragma is designed to be a one-way street).
907 is_utf8_char(s) returns true if the pointer points to a valid UTF-8
912 is_utf8_string(buf, len) returns true if the len bytes of the buffer
917 UTF8SKIP(buf) will return the number of bytes in the UTF-8 encoded
918 character in the buffer. UNISKIP(chr) will return the number of bytes
919 required to UTF-8-encode the Unicode character code point. UTF8SKIP()
920 is useful for example for iterating over the characters of a UTF-8
921 encoded buffer; UNISKIP() is useful for example in computing
922 the size required for a UTF-8 encoded buffer.
926 utf8_distance(a, b) will tell the distance in characters between the
927 two pointers pointing to the same UTF-8 encoded buffer.
931 utf8_hop(s, off) will return a pointer to an UTF-8 encoded buffer that
932 is C<off> (positive or negative) Unicode characters displaced from the
933 UTF-8 buffer C<s>. Be careful not to overstep the buffer: utf8_hop()
934 will merrily run off the end or the beginning if told to do so.
938 pv_uni_display(dsv, spv, len, pvlim, flags) and sv_uni_display(dsv,
939 ssv, pvlim, flags) are useful for debug output of Unicode strings and
940 scalars. By default they are useful only for debug: they display
941 B<all> characters as hexadecimal code points, but with the flags
942 UNI_DISPLAY_ISPRINT and UNI_DISPLAY_BACKSLASH you can make the output
947 ibcmp_utf8(s1, pe1, u1, l1, u1, s2, pe2, l2, u2) can be used to
948 compare two strings case-insensitively in Unicode.
949 (For case-sensitive comparisons you can just use memEQ() and memNE()
954 For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h>
955 in the Perl source code distribution.
959 Use of locales with Unicode data may lead to odd results. Currently
960 there is some attempt to apply 8-bit locale info to characters in the
961 range 0..255, but this is demonstrably incorrect for locales that use
962 characters above that range when mapped into Unicode. It will also
963 tend to run slower. Use of locales with Unicode is discouraged.
965 Some functions are slower when working on UTF-8 encoded strings than
966 on byte encoded strings. All functions that need to hop over
967 characters such as length(), substr() or index() can work B<much>
968 faster when the underlying data are byte-encoded. Witness the
975 our $u = our $b = "x" x $l;
976 substr($u,0,1) = "\x{100}";
978 LENGTH_B => q{ length($b) },
979 LENGTH_U => q{ length($u) },
980 SUBSTR_B => q{ substr($b, $l/4, $l/2) },
981 SUBSTR_U => q{ substr($u, $l/4, $l/2) },
984 Benchmark: running LENGTH_B, LENGTH_U, SUBSTR_B, SUBSTR_U for at least 2 CPU seconds...
985 LENGTH_B: 2 wallclock secs ( 2.36 usr + 0.00 sys = 2.36 CPU) @ 5649983.05/s (n=13333960)
986 LENGTH_U: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 12155.45/s (n=25648)
987 SUBSTR_B: 3 wallclock secs ( 2.16 usr + 0.00 sys = 2.16 CPU) @ 374480.09/s (n=808877)
988 SUBSTR_U: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU) @ 6791.00/s (n=14329)
990 The numbers show an incredible slowness on long UTF-8 strings and you
991 should carefully avoid to use these functions within tight loops. For
992 example if you want to iterate over characters, it is infinitely
993 better to split into an array than to use substr, as the following
1000 our $u = our $b = "x" x $l;
1001 substr($u,0,1) = "\x{100}";
1003 SPLIT_B => q{ for my $c (split //, $b){} },
1004 SPLIT_U => q{ for my $c (split //, $u){} },
1005 SUBSTR_B => q{ for my $i (0..length($b)-1){my $c = substr($b,$i,1);} },
1006 SUBSTR_U => q{ for my $i (0..length($u)-1){my $c = substr($u,$i,1);} },
1009 Benchmark: running SPLIT_B, SPLIT_U, SUBSTR_B, SUBSTR_U for at least 5 CPU seconds...
1010 SPLIT_B: 6 wallclock secs ( 5.29 usr + 0.00 sys = 5.29 CPU) @ 56.14/s (n=297)
1011 SPLIT_U: 5 wallclock secs ( 5.17 usr + 0.01 sys = 5.18 CPU) @ 55.21/s (n=286)
1012 SUBSTR_B: 5 wallclock secs ( 5.34 usr + 0.00 sys = 5.34 CPU) @ 123.22/s (n=658)
1013 SUBSTR_U: 7 wallclock secs ( 6.20 usr + 0.00 sys = 6.20 CPU) @ 0.81/s (n=5)
1015 You see, the algorithm based on substr() was faster with byte encoded
1016 data but it is pathologically slow with UTF-8 data.
1020 L<perluniintro>, L<encoding>, L<Encode>, L<open>, L<utf8>, L<bytes>,
1021 L<perlretut>, L<perlvar/"${^WIDE_SYSTEM_CALLS}">