This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #70748] threads panic in del_backref
[perl5.git] / pod / perlunicode.pod
CommitLineData
393fec97
GS
1=head1 NAME
2
3perlunicode - Unicode support in Perl
4
5=head1 DESCRIPTION
6
0a1f2d14 7=head2 Important Caveats
21bad921 8
376d9008 9Unicode support is an extensive requirement. While Perl does not
c349b1b9
JH
10implement the Unicode standard or the accompanying technical reports
11from cover to cover, Perl does support many Unicode features.
21bad921 12
2575c402 13People who want to learn to use Unicode in Perl, should probably read
e4911a48
RS
14L<the Perl Unicode tutorial, perlunitut|perlunitut>, before reading
15this reference document.
2575c402 16
13a2d996 17=over 4
21bad921 18
fae2c0fb 19=item Input and Output Layers
21bad921 20
376d9008 21Perl knows when a filehandle uses Perl's internal Unicode encodings
1bfb14c4
JH
22(UTF-8, or UTF-EBCDIC if in EBCDIC) if the filehandle is opened with
23the ":utf8" layer. Other encodings can be converted to Perl's
24encoding on input or from Perl's encoding on output by use of the
25":encoding(...)" layer. See L<open>.
c349b1b9 26
2575c402 27To indicate that Perl source itself is in UTF-8, use C<use utf8;>.
21bad921
GS
28
29=item Regular Expressions
30
c349b1b9 31The regular expression compiler produces polymorphic opcodes. That is,
376d9008 32the pattern adapts to the data and automatically switches to the Unicode
2575c402
JW
33character scheme when presented with data that is internally encoded in
34UTF-8 -- or instead uses a traditional byte scheme when presented with
35byte data.
21bad921 36
ad0029c4 37=item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts
21bad921 38
376d9008
JB
39As a compatibility measure, the C<use utf8> pragma must be explicitly
40included to enable recognition of UTF-8 in the Perl scripts themselves
1bfb14c4
JH
41(in string or regular expression literals, or in identifier names) on
42ASCII-based machines or to recognize UTF-EBCDIC on EBCDIC-based
376d9008 43machines. B<These are the only times when an explicit C<use utf8>
8f8cf39c 44is needed.> See L<utf8>.
21bad921 45
7aa207d6
JH
46=item BOM-marked scripts and UTF-16 scripts autodetected
47
48If a Perl script begins marked with the Unicode BOM (UTF-16LE, UTF16-BE,
49or UTF-8), or if the script looks like non-BOM-marked UTF-16 of either
50endianness, Perl will correctly read in the script as Unicode.
51(BOMless UTF-8 cannot be effectively recognized or differentiated from
52ISO 8859-1 or other eight-bit encodings.)
53
990e18f7
AT
54=item C<use encoding> needed to upgrade non-Latin-1 byte strings
55
38a44b82 56By default, there is a fundamental asymmetry in Perl's Unicode model:
990e18f7
AT
57implicit upgrading from byte strings to Unicode strings assumes that
58they were encoded in I<ISO 8859-1 (Latin-1)>, but Unicode strings are
59downgraded with UTF-8 encoding. This happens because the first 256
51f494cc 60codepoints in Unicode happens to agree with Latin-1.
990e18f7 61
990e18f7
AT
62See L</"Byte and Character Semantics"> for more details.
63
21bad921
GS
64=back
65
376d9008 66=head2 Byte and Character Semantics
393fec97 67
376d9008 68Beginning with version 5.6, Perl uses logically-wide characters to
3e4dbfed 69represent strings internally.
393fec97 70
376d9008
JB
71In future, Perl-level operations will be expected to work with
72characters rather than bytes.
393fec97 73
376d9008 74However, as an interim compatibility measure, Perl aims to
75daf61c
JH
75provide a safe migration path from byte semantics to character
76semantics for programs. For operations where Perl can unambiguously
376d9008 77decide that the input data are characters, Perl switches to
75daf61c
JH
78character semantics. For operations where this determination cannot
79be made without additional information from the user, Perl decides in
376d9008 80favor of compatibility and chooses to use byte semantics.
8cbd9a7a 81
51f494cc 82Under byte semantics, when C<use locale> is in effect, Perl uses the
2bbc8d55
SP
83semantics associated with the current locale. Absent a C<use locale>, Perl
84currently uses US-ASCII (or Basic Latin in Unicode terminology) byte semantics,
85meaning that characters whose ordinal numbers are in the range 128 - 255 are
86undefined except for their ordinal numbers. This means that none have case
87(upper and lower), nor are any a member of character classes, like C<[:alpha:]>
88or C<\w>.
89(But all do belong to the C<\W> class or the Perl regular expression extension
90C<[:^alpha:]>.)
91
8cbd9a7a 92This behavior preserves compatibility with earlier versions of Perl,
376d9008
JB
93which allowed byte semantics in Perl operations only if
94none of the program's inputs were marked as being as source of Unicode
8cbd9a7a
GS
95character data. Such data may come from filehandles, from calls to
96external programs, from information provided by the system (such as %ENV),
21bad921 97or from literals and constants in the source text.
8cbd9a7a 98
376d9008
JB
99The C<bytes> pragma will always, regardless of platform, force byte
100semantics in a particular lexical scope. See L<bytes>.
8cbd9a7a
GS
101
102The C<utf8> pragma is primarily a compatibility device that enables
75daf61c 103recognition of UTF-(8|EBCDIC) in literals encountered by the parser.
376d9008
JB
104Note that this pragma is only required while Perl defaults to byte
105semantics; when character semantics become the default, this pragma
106may become a no-op. See L<utf8>.
107
108Unless explicitly stated, Perl operators use character semantics
109for Unicode data and byte semantics for non-Unicode data.
110The decision to use character semantics is made transparently. If
111input data comes from a Unicode source--for example, if a character
fae2c0fb 112encoding layer is added to a filehandle or a literal Unicode
376d9008
JB
113string constant appears in a program--character semantics apply.
114Otherwise, byte semantics are in effect. The C<bytes> pragma should
115be used to force byte semantics on Unicode data.
116
117If strings operating under byte semantics and strings with Unicode
51f494cc 118character data are concatenated, the new string will have
42bde815 119character semantics. This can cause surprises: See L</BUGS>, below
7dedd01f 120
feda178f 121Under character semantics, many operations that formerly operated on
376d9008 122bytes now operate on characters. A character in Perl is
feda178f 123logically just a number ranging from 0 to 2**31 or so. Larger
376d9008
JB
124characters may encode into longer sequences of bytes internally, but
125this internal detail is mostly hidden for Perl code.
126See L<perluniintro> for more.
393fec97 127
376d9008 128=head2 Effects of Character Semantics
393fec97
GS
129
130Character semantics have the following effects:
131
132=over 4
133
134=item *
135
376d9008 136Strings--including hash keys--and regular expression patterns may
574c8022 137contain characters that have an ordinal value larger than 255.
393fec97 138
2575c402
JW
139If you use a Unicode editor to edit your program, Unicode characters may
140occur directly within the literal strings in UTF-8 encoding, or UTF-16.
141(The former requires a BOM or C<use utf8>, the latter requires a BOM.)
3e4dbfed 142
2575c402
JW
143Unicode characters can also be added to a string by using the C<\x{...}>
144notation. The Unicode code for the desired character, in hexadecimal,
145should be placed in the braces. For instance, a smiley face is
2bbc8d55 146C<\x{263A}>. This encoding scheme works for all characters, but
2575c402
JW
147for characters under 0x100, note that Perl may use an 8 bit encoding
148internally, for optimization and/or backward compatibility.
3e4dbfed
JF
149
150Additionally, if you
574c8022 151
3e4dbfed 152 use charnames ':full';
574c8022 153
1bfb14c4
JH
154you can use the C<\N{...}> notation and put the official Unicode
155character name within the braces, such as C<\N{WHITE SMILING FACE}>.
376d9008 156
393fec97
GS
157=item *
158
574c8022
JH
159If an appropriate L<encoding> is specified, identifiers within the
160Perl script may contain Unicode alphanumeric characters, including
376d9008
JB
161ideographs. Perl does not currently attempt to canonicalize variable
162names.
393fec97 163
393fec97
GS
164=item *
165
1bfb14c4 166Regular expressions match characters instead of bytes. "." matches
2575c402 167a character instead of a byte.
393fec97 168
393fec97
GS
169=item *
170
171Character classes in regular expressions match characters instead of
376d9008 172bytes and match against the character properties specified in the
1bfb14c4 173Unicode properties database. C<\w> can be used to match a Japanese
75daf61c 174ideograph, for instance.
393fec97 175
393fec97
GS
176=item *
177
eb0cc9e3 178Named Unicode properties, scripts, and block ranges may be used like
376d9008 179character classes via the C<\p{}> "matches property" construct and
822502e5
TS
180the C<\P{}> negation, "doesn't match property".
181
2575c402 182See L</"Unicode Character Properties"> for more details.
822502e5
TS
183
184You can define your own character properties and use them
185in the regular expression with the C<\p{}> or C<\P{}> construct.
186
187See L</"User-Defined Character Properties"> for more details.
188
189=item *
190
51f494cc
KW
191The special pattern C<\X> matches a logical character, an C<extended grapheme
192cluster> in Standardese. In Unicode what appears to the user to be a single
193character, for example an accented C<G>, may in fact be composed of a sequence
194of characters, in this case a C<G> followed by an accent character. C<\X>
195will match the entire sequence.
822502e5
TS
196
197=item *
198
199The C<tr///> operator translates characters instead of bytes. Note
200that the C<tr///CU> functionality has been removed. For similar
201functionality see pack('U0', ...) and pack('C0', ...).
202
203=item *
204
205Case translation operators use the Unicode case translation tables
206when character input is provided. Note that C<uc()>, or C<\U> in
207interpolated strings, translates to uppercase, while C<ucfirst>,
208or C<\u> in interpolated strings, translates to titlecase in languages
209that make the distinction.
210
211=item *
212
213Most operators that deal with positions or lengths in a string will
214automatically switch to using character positions, including
215C<chop()>, C<chomp()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>,
216C<sprintf()>, C<write()>, and C<length()>. An operator that
51f494cc
KW
217specifically does not switch is C<vec()>. Operators that really don't
218care include operators that treat strings as a bucket of bits such as
822502e5
TS
219C<sort()>, and operators dealing with filenames.
220
221=item *
222
51f494cc 223The C<pack()>/C<unpack()> letter C<C> does I<not> change, since it is often
822502e5
TS
224used for byte-oriented formats. Again, think C<char> in the C language.
225
226There is a new C<U> specifier that converts between Unicode characters
227and code points. There is also a C<W> specifier that is the equivalent of
228C<chr>/C<ord> and properly handles character values even if they are above 255.
229
230=item *
231
232The C<chr()> and C<ord()> functions work on characters, similar to
233C<pack("W")> and C<unpack("W")>, I<not> C<pack("C")> and
234C<unpack("C")>. C<pack("C")> and C<unpack("C")> are methods for
235emulating byte-oriented C<chr()> and C<ord()> on Unicode strings.
236While these methods reveal the internal encoding of Unicode strings,
237that is not something one normally needs to care about at all.
238
239=item *
240
241The bit string operators, C<& | ^ ~>, can operate on character data.
242However, for backward compatibility, such as when using bit string
243operations when characters are all less than 256 in ordinal value, one
244should not use C<~> (the bit complement) with characters of both
245values less than 256 and values greater than 256. Most importantly,
246DeMorgan's laws (C<~($x|$y) eq ~$x&~$y> and C<~($x&$y) eq ~$x|~$y>)
247will not hold. The reason for this mathematical I<faux pas> is that
248the complement cannot return B<both> the 8-bit (byte-wide) bit
249complement B<and> the full character-wide bit complement.
250
251=item *
252
253lc(), uc(), lcfirst(), and ucfirst() work for the following cases:
254
255=over 8
256
257=item *
258
259the case mapping is from a single Unicode character to another
260single Unicode character, or
261
262=item *
263
264the case mapping is from a single Unicode character to more
265than one Unicode character.
266
267=back
268
269Things to do with locales (Lithuanian, Turkish, Azeri) do B<not> work
270since Perl does not understand the concept of Unicode locales.
271
272See the Unicode Technical Report #21, Case Mappings, for more details.
273
274But you can also define your own mappings to be used in the lc(),
275lcfirst(), uc(), and ucfirst() (or their string-inlined versions).
276
277See L</"User-Defined Case Mappings"> for more details.
278
279=back
280
281=over 4
282
283=item *
284
285And finally, C<scalar reverse()> reverses by character rather than by byte.
286
287=back
288
289=head2 Unicode Character Properties
290
51f494cc
KW
291Most Unicode character properties are accessible by using regular expressions.
292They are used like character classes via the C<\p{}> "matches property"
293construct and the C<\P{}> negation, "doesn't match property".
294
295For instance, C<\p{Uppercase}> matches any character with the Unicode
296"Uppercase" property, while C<\p{L}> matches any character with a
297General_Category of "L" (letter) property. Brackets are not
298required for single letter properties, so C<\p{L}> is equivalent to C<\pL>.
299
300More formally, C<\p{Uppercase}> matches any character whose Uppercase property
301value is True, and C<\P{Uppercase}> matches any character whose Uppercase
302property value is False, and they could have been written as
303C<\p{Uppercase=True}> and C<\p{Uppercase=False}>, respectively
304
305This formality is needed when properties are not binary, that is if they can
306take on more values than just True and False. For example, the Bidi_Class (see
307L</"Bidirectional Character Types"> below), can take on a number of different
308values, such as Left, Right, Whitespace, and others. To match these, one needs
309to specify the property name (Bidi_Class), and the value being matched with
310(Left, Right, etc.). This is done, as in the examples above, by having the two
311components separated by an equal sign (or interchangeably, a colon), like
312C<\p{Bidi_Class: Left}>.
313
314All Unicode-defined character properties may be written in these compound forms
315of C<\p{property=value}> or C<\p{property:value}>, but Perl provides some
316additional properties that are written only in the single form, as well as
317single-form short-cuts for all binary properties and certain others described
318below, in which you may omit the property name and the equals or colon
319separator.
320
321Most Unicode character properties have at least two synonyms (or aliases if you
322prefer), a short one that is easier to type, and a longer one which is more
323descriptive and hence it is easier to understand what it means. Thus the "L"
324and "Letter" above are equivalent and can be used interchangeably. Likewise,
325"Upper" is a synonym for "Uppercase", and we could have written
326C<\p{Uppercase}> equivalently as C<\p{Upper}>. Also, there are typically
327various synonyms for the values the property can be. For binary properties,
328"True" has 3 synonyms: "T", "Yes", and "Y"; and "False has correspondingly "F",
329"No", and "N". But be careful. A short form of a value for one property may
330not mean the same thing as the same name for another. Thus, for the
331General_Category property, "L" means "Letter", but for the Bidi_Class property,
332"L" means "Left". A complete list of properties and synonyms is in
333L<perluniprops>.
334
335Upper/lower case differences in the property names and values are irrelevant,
336thus C<\p{Upper}> means the same thing as C<\p{upper}> or even C<\p{UpPeR}>.
337Similarly, you can add or subtract underscores anywhere in the middle of a
338word, so that these are also equivalent to C<\p{U_p_p_e_r}>. And white space
339is irrelevant adjacent to non-word characters, such as the braces and the equals
340or colon separators so C<\p{ Upper }> and C<\p{ Upper_case : Y }> are
341equivalent to these as well. In fact, in most cases, white space and even
342hyphens can be added or deleted anywhere. So even C<\p{ Up-per case = Yes}> is
343equivalent. All this is called "loose-matching" by Unicode. The few places
344where stricter matching is employed is in the middle of numbers, and the Perl
345extension properties that begin or end with an underscore. Stricter matching
346cares about white space (except adjacent to the non-word characters) and
347hyphens, and non-interior underscores.
4193bef7 348
376d9008
JB
349You can also use negation in both C<\p{}> and C<\P{}> by introducing a caret
350(^) between the first brace and the property name: C<\p{^Tamil}> is
eb0cc9e3 351equal to C<\P{Tamil}>.
4193bef7 352
51f494cc 353=head3 B<General_Category>
14bb0a9a 354
51f494cc
KW
355Every Unicode character is assigned a general category, which is the "most
356usual categorization of a character" (from
357L<http://www.unicode.org/reports/tr44>).
822502e5 358
51f494cc
KW
359The compound way of writing these is like C<{\p{General_Category=Number}>
360(short, C<\p{gc:n}>). But Perl furnishes shortcuts in which everything up
361through the equal or colon separator is omitted. So you can instead just write
362C<\pN>.
822502e5 363
51f494cc 364Here are the short and long forms of the General Category properties:
393fec97 365
d73e5302
JH
366 Short Long
367
368 L Letter
51f494cc
KW
369 LC, L& Cased_Letter (that is: [\p{Ll}\p{Lu}\p{Lt}])
370 Lu Uppercase_Letter
371 Ll Lowercase_Letter
372 Lt Titlecase_Letter
373 Lm Modifier_Letter
374 Lo Other_Letter
d73e5302
JH
375
376 M Mark
51f494cc
KW
377 Mn Nonspacing_Mark
378 Mc Spacing_Mark
379 Me Enclosing_Mark
d73e5302
JH
380
381 N Number
51f494cc
KW
382 Nd Decimal_Number (also Digit)
383 Nl Letter_Number
384 No Other_Number
385
386 P Punctuation (also Punct)
387 Pc Connector_Punctuation
388 Pd Dash_Punctuation
389 Ps Open_Punctuation
390 Pe Close_Punctuation
391 Pi Initial_Punctuation
d73e5302 392 (may behave like Ps or Pe depending on usage)
51f494cc 393 Pf Final_Punctuation
d73e5302 394 (may behave like Ps or Pe depending on usage)
51f494cc 395 Po Other_Punctuation
d73e5302
JH
396
397 S Symbol
51f494cc
KW
398 Sm Math_Symbol
399 Sc Currency_Symbol
400 Sk Modifier_Symbol
401 So Other_Symbol
d73e5302
JH
402
403 Z Separator
51f494cc
KW
404 Zs Space_Separator
405 Zl Line_Separator
406 Zp Paragraph_Separator
d73e5302
JH
407
408 C Other
51f494cc 409 Cc Control (also Cntrl)
e150c829 410 Cf Format
eb0cc9e3 411 Cs Surrogate (not usable)
51f494cc 412 Co Private_Use
e150c829 413 Cn Unassigned
1ac13f9a 414
376d9008 415Single-letter properties match all characters in any of the
3e4dbfed 416two-letter sub-properties starting with the same letter.
12ac2576
JP
417C<LC> and C<L&> are special cases, which are aliases for the set of
418C<Ll>, C<Lu>, and C<Lt>.
32293815 419
eb0cc9e3 420Because Perl hides the need for the user to understand the internal
1bfb14c4
JH
421representation of Unicode characters, there is no need to implement
422the somewhat messy concept of surrogates. C<Cs> is therefore not
eb0cc9e3 423supported.
d73e5302 424
51f494cc 425=head3 B<Bidirectional Character Types>
822502e5 426
376d9008 427Because scripts differ in their directionality--Hebrew is
12ac2576 428written right to left, for example--Unicode supplies these properties in
51f494cc 429the Bidi_Class class:
32293815 430
eb0cc9e3 431 Property Meaning
92e830a9 432
12ac2576
JP
433 L Left-to-Right
434 LRE Left-to-Right Embedding
435 LRO Left-to-Right Override
436 R Right-to-Left
51f494cc 437 AL Arabic Letter
12ac2576
JP
438 RLE Right-to-Left Embedding
439 RLO Right-to-Left Override
440 PDF Pop Directional Format
441 EN European Number
51f494cc
KW
442 ES European Separator
443 ET European Terminator
12ac2576 444 AN Arabic Number
51f494cc 445 CS Common Separator
12ac2576
JP
446 NSM Non-Spacing Mark
447 BN Boundary Neutral
448 B Paragraph Separator
449 S Segment Separator
450 WS Whitespace
451 ON Other Neutrals
452
51f494cc
KW
453This property is always written in the compound form.
454For example, C<\p{Bidi_Class:R}> matches characters that are normally
eb0cc9e3
JH
455written right to left.
456
51f494cc
KW
457=head3 B<Scripts>
458
459The world's languages are written in a number of scripts. This sentence is
460written in Latin, while Russian is written in Cyrllic, and Greek is written in,
461well, Greek; Japanese mainly in Hiragana or Katakana. There are many more.
462
463The Unicode Script property gives what script a given character is in,
464and can be matched with the compound form like C<\p{Script=Hebrew}> (short:
465C<\p{sc=hebr}>). Perl furnishes shortcuts for all script names. You can omit
466everything up through the equals (or colon), and simply write C<\p{Latin}> or
467C<\P{Cyrillic}>.
468
469A complete list of scripts and their shortcuts is in L<perluniprops>.
470
471=head3 B<Extended property classes>
472
473There are many more property classes than the basic ones described here,
474including some Perl extensions.
475A complete list is in L<perluniprops>.
476The extensions are more fully described in L<perlrecharclass>
477
478=head3 B<Use of "Is" Prefix>
822502e5 479
1bfb14c4 480For backward compatibility (with Perl 5.6), all properties mentioned
51f494cc
KW
481so far may have C<Is> or C<Is_> prepended to their name, so C<\P{Is_Lu}>, for
482example, is equal to C<\P{Lu}>, and C<\p{IsScript:Arabic}> is equal to
483C<\p{Arabic}>.
eb0cc9e3 484
51f494cc 485=head3 B<Blocks>
2796c109 486
1bfb14c4
JH
487In addition to B<scripts>, Unicode also defines B<blocks> of
488characters. The difference between scripts and blocks is that the
489concept of scripts is closer to natural languages, while the concept
51f494cc
KW
490of blocks is more of an artificial grouping based on groups of Unicode
491characters with consecutive ordinal values. For example, the C<Basic Latin>
492block is all characters whose ordinals are between 0 and 127, inclusive, in
493other words, the ASCII characters. The C<Latin> script contains some letters
494from this block as well as several more, like C<Latin-1 Supplement>,
495C<Latin Extended-A>, I<etc.>, but it does not contain all the characters from
496those blocks. It does not, for example, contain digits, because digits are
497shared across many scripts. Digits and similar groups, like punctuation, are in
498the script called C<Common>. There is also a script called C<Inherited> for
499characters that modify other characters, and inherit the script value of the
500controlling character.
501
502For more about scripts versus blocks, see UAX#24 "Unicode Script Property":
503L<http://www.unicode.org/reports/tr24>
504
505The Script property is likely to be the one you want to use when processing
506natural language; the Block property may be useful in working with the nuts and
507bolts of Unicode.
508
509Block names are matched in the compound form, like C<\p{Block: Arrows}> or
510C<\p{Blk=Hebrew}>. Unlike most other properties only a few block names have a
511Unicode-defined short name. But Perl does provide a (slight) shortcut: You
512can say, for example C<\p{In_Arrows}> or C<\p{In_Hebrew}>. For backwards
513compatibility, the C<In> prefix may be omitted if there is no naming conflict
514with a script or any other property, and you can even use an C<Is> prefix
515instead in those cases. But it is not a good idea to do this, for a couple
516reasons:
517
518=over 4
519
520=item 1
521
522It is confusing. There are many naming conflicts, and you may forget some.
523For example, \p{Hebrew} means the I<script> Hebrew, and NOT the I<block>
524Hebrew. But would you remember that 6 months from now?
525
526=item 2
527
528It is unstable. A new version of Unicode may pre-empt the current meaning by
529creating a property with the same name. There was a time in very early Unicode
530releases when \p{Hebrew} would have matched the I<block> Hebrew; now it
531doesn't.
32293815 532
393fec97
GS
533=back
534
51f494cc
KW
535Some people just prefer to always use C<\p{Block: foo}> and C<\p{Script: bar}>
536instead of the shortcuts, for clarity, and because they can't remember the
537difference between 'In' and 'Is' anyway (or aren't confident that those who
538eventually will read their code will know).
539
540A complete list of blocks and their shortcuts is in L<perluniprops>.
541
376d9008 542=head2 User-Defined Character Properties
491fd90a 543
51f494cc
KW
544You can define your own binary character properties by defining subroutines
545whose names begin with "In" or "Is". The subroutines can be defined in any
546package. The user-defined properties can be used in the regular expression
547C<\p> and C<\P> constructs; if you are using a user-defined property from a
548package other than the one you are in, you must specify its package in the
549C<\p> or C<\P> construct.
bac0b425 550
51f494cc 551 # assuming property Is_Foreign defined in Lang::
bac0b425
JP
552 package main; # property package name required
553 if ($txt =~ /\p{Lang::IsForeign}+/) { ... }
554
555 package Lang; # property package name not required
556 if ($txt =~ /\p{IsForeign}+/) { ... }
557
558
559Note that the effect is compile-time and immutable once defined.
491fd90a 560
376d9008
JB
561The subroutines must return a specially-formatted string, with one
562or more newline-separated lines. Each line must be one of the following:
491fd90a
JH
563
564=over 4
565
566=item *
567
510254c9
A
568A single hexadecimal number denoting a Unicode code point to include.
569
570=item *
571
99a6b1f0 572Two hexadecimal numbers separated by horizontal whitespace (space or
376d9008 573tabular characters) denoting a range of Unicode code points to include.
491fd90a
JH
574
575=item *
576
376d9008 577Something to include, prefixed by "+": a built-in character
bac0b425
JP
578property (prefixed by "utf8::") or a user-defined character property,
579to represent all the characters in that property; two hexadecimal code
580points for a range; or a single hexadecimal code point.
491fd90a
JH
581
582=item *
583
376d9008 584Something to exclude, prefixed by "-": an existing character
bac0b425
JP
585property (prefixed by "utf8::") or a user-defined character property,
586to represent all the characters in that property; two hexadecimal code
587points for a range; or a single hexadecimal code point.
491fd90a
JH
588
589=item *
590
376d9008 591Something to negate, prefixed "!": an existing character
bac0b425
JP
592property (prefixed by "utf8::") or a user-defined character property,
593to represent all the characters in that property; two hexadecimal code
594points for a range; or a single hexadecimal code point.
595
596=item *
597
598Something to intersect with, prefixed by "&": an existing character
599property (prefixed by "utf8::") or a user-defined character property,
600for all the characters except the characters in the property; two
601hexadecimal code points for a range; or a single hexadecimal code point.
491fd90a
JH
602
603=back
604
605For example, to define a property that covers both the Japanese
606syllabaries (hiragana and katakana), you can define
607
608 sub InKana {
d5822f25
A
609 return <<END;
610 3040\t309F
611 30A0\t30FF
491fd90a
JH
612 END
613 }
614
d5822f25
A
615Imagine that the here-doc end marker is at the beginning of the line.
616Now you can use C<\p{InKana}> and C<\P{InKana}>.
491fd90a
JH
617
618You could also have used the existing block property names:
619
620 sub InKana {
621 return <<'END';
622 +utf8::InHiragana
623 +utf8::InKatakana
624 END
625 }
626
627Suppose you wanted to match only the allocated characters,
d5822f25 628not the raw block ranges: in other words, you want to remove
491fd90a
JH
629the non-characters:
630
631 sub InKana {
632 return <<'END';
633 +utf8::InHiragana
634 +utf8::InKatakana
635 -utf8::IsCn
636 END
637 }
638
639The negation is useful for defining (surprise!) negated classes.
640
641 sub InNotKana {
642 return <<'END';
643 !utf8::InHiragana
644 -utf8::InKatakana
645 +utf8::IsCn
646 END
647 }
648
bac0b425
JP
649Intersection is useful for getting the common characters matched by
650two (or more) classes.
651
652 sub InFooAndBar {
653 return <<'END';
654 +main::Foo
655 &main::Bar
656 END
657 }
658
659It's important to remember not to use "&" for the first set -- that
660would be intersecting with nothing (resulting in an empty set).
661
822502e5
TS
662=head2 User-Defined Case Mappings
663
3a2263fe
RGS
664You can also define your own mappings to be used in the lc(),
665lcfirst(), uc(), and ucfirst() (or their string-inlined versions).
822502e5 666The principle is similar to that of user-defined character
51f494cc 667properties: to define subroutines
3a2263fe
RGS
668with names like C<ToLower> (for lc() and lcfirst()), C<ToTitle> (for
669the first character in ucfirst()), and C<ToUpper> (for uc(), and the
670rest of the characters in ucfirst()).
671
51f494cc
KW
672The string returned by the subroutines needs to be two hexadecimal numbers
673separated by two tabulators: the source code point and the destination code
674point. For example:
3a2263fe
RGS
675
676 sub ToUpper {
677 return <<END;
51f494cc 678 0061\t\t0041
3a2263fe
RGS
679 END
680 }
681
51f494cc
KW
682defines an uc() mapping that causes only the character "a"
683to be mapped to "A"; all other characters will remain unchanged.
3a2263fe 684
51f494cc
KW
685(For serious hackers only) The above means you have to furnish a complete
686mapping; you can't just override a couple of characters and leave the rest
687unchanged. You can find all the mappings in the directory
688C<$Config{privlib}>/F<unicore/To/>. The mapping data is returned as the
689here-document, and the C<utf8::ToSpecFoo> are special exception mappings
690derived from <$Config{privlib}>/F<unicore/SpecialCasing.txt>. The C<Digit> and
691C<Fold> mappings that one can see in the directory are not directly
692user-accessible, one can use either the C<Unicode::UCD> module, or just match
693case-insensitively (that's when the C<Fold> mapping is used).
3a2263fe 694
51f494cc
KW
695The mappings will only take effect on scalars that have been marked as having
696Unicode characters, for example by using C<utf8::upgrade()>.
697Old byte-style strings are not affected.
3a2263fe 698
51f494cc 699The mappings are in effect for the package they are defined in.
3a2263fe 700
376d9008 701=head2 Character Encodings for Input and Output
8cbd9a7a 702
7221edc9 703See L<Encode>.
8cbd9a7a 704
c29a771d 705=head2 Unicode Regular Expression Support Level
776f8809 706
376d9008
JB
707The following list of Unicode support for regular expressions describes
708all the features currently supported. The references to "Level N"
8158862b
TS
709and the section numbers refer to the Unicode Technical Standard #18,
710"Unicode Regular Expressions", version 11, in May 2005.
776f8809
JH
711
712=over 4
713
714=item *
715
716Level 1 - Basic Unicode Support
717
8158862b
TS
718 RL1.1 Hex Notation - done [1]
719 RL1.2 Properties - done [2][3]
720 RL1.2a Compatibility Properties - done [4]
721 RL1.3 Subtraction and Intersection - MISSING [5]
722 RL1.4 Simple Word Boundaries - done [6]
723 RL1.5 Simple Loose Matches - done [7]
724 RL1.6 Line Boundaries - MISSING [8]
725 RL1.7 Supplementary Code Points - done [9]
726
727 [1] \x{...}
728 [2] \p{...} \P{...}
729 [3] supports not only minimal list (general category, scripts,
730 Alphabetic, Lowercase, Uppercase, WhiteSpace,
731 NoncharacterCodePoint, DefaultIgnorableCodePoint, Any,
732 ASCII, Assigned), but also bidirectional types, blocks, etc.
ea8b8ad2 733 (see "Unicode Character Properties")
8158862b
TS
734 [4] \d \D \s \S \w \W \X [:prop:] [:^prop:]
735 [5] can use regular expression look-ahead [a] or
736 user-defined character properties [b] to emulate set operations
737 [6] \b \B
738 [7] note that Perl does Full case-folding in matching, not Simple:
2bbc8d55
SP
739 for example U+1F88 is equivalent to U+1F00 U+03B9,
740 not with 1F80. This difference matters mainly for certain Greek
376d9008
JB
741 capital letters with certain modifiers: the Full case-folding
742 decomposes the letter, while the Simple case-folding would map
e0f9d4a8 743 it to a single character.
8158862b
TS
744 [8] should do ^ and $ also on U+000B (\v in C), FF (\f), CR (\r),
745 CRLF (\r\n), NEL (U+0085), LS (U+2028), and PS (U+2029);
746 should also affect <>, $., and script line numbers;
747 should not split lines within CRLF [c] (i.e. there is no empty
748 line between \r and \n)
749 [9] UTF-8/UTF-EBDDIC used in perl allows not only U+10000 to U+10FFFF
750 but also beyond U+10FFFF [d]
7207e29d 751
237bad5b 752[a] You can mimic class subtraction using lookahead.
8158862b 753For example, what UTS#18 might write as
29bdacb8 754
dbe420b4
JH
755 [{Greek}-[{UNASSIGNED}]]
756
757in Perl can be written as:
758
1d81abf3
JH
759 (?!\p{Unassigned})\p{InGreekAndCoptic}
760 (?=\p{Assigned})\p{InGreekAndCoptic}
dbe420b4
JH
761
762But in this particular example, you probably really want
763
1bfb14c4 764 \p{GreekAndCoptic}
dbe420b4
JH
765
766which will match assigned characters known to be part of the Greek script.
29bdacb8 767
5ca1ac52 768Also see the Unicode::Regex::Set module, it does implement the full
8158862b
TS
769UTS#18 grouping, intersection, union, and removal (subtraction) syntax.
770
771[b] '+' for union, '-' for removal (set-difference), '&' for intersection
772(see L</"User-Defined Character Properties">)
773
774[c] Try the C<:crlf> layer (see L<PerlIO>).
5ca1ac52 775
8158862b
TS
776[d] Avoid C<use warning 'utf8';> (or say C<no warning 'utf8';>) to allow
777U+FFFF (C<\x{FFFF}>).
237bad5b 778
776f8809
JH
779=item *
780
781Level 2 - Extended Unicode Support
782
8158862b
TS
783 RL2.1 Canonical Equivalents - MISSING [10][11]
784 RL2.2 Default Grapheme Clusters - MISSING [12][13]
785 RL2.3 Default Word Boundaries - MISSING [14]
786 RL2.4 Default Loose Matches - MISSING [15]
787 RL2.5 Name Properties - MISSING [16]
788 RL2.6 Wildcard Properties - MISSING
789
790 [10] see UAX#15 "Unicode Normalization Forms"
791 [11] have Unicode::Normalize but not integrated to regexes
792 [12] have \X but at this level . should equal that
793 [13] UAX#29 "Text Boundaries" considers CRLF and Hangul syllable
794 clusters as a single grapheme cluster.
795 [14] see UAX#29, Word Boundaries
796 [15] see UAX#21 "Case Mappings"
797 [16] have \N{...} but neither compute names of CJK Ideographs
798 and Hangul Syllables nor use a loose match [e]
799
800[e] C<\N{...}> allows namespaces (see L<charnames>).
776f8809
JH
801
802=item *
803
8158862b
TS
804Level 3 - Tailored Support
805
806 RL3.1 Tailored Punctuation - MISSING
807 RL3.2 Tailored Grapheme Clusters - MISSING [17][18]
808 RL3.3 Tailored Word Boundaries - MISSING
809 RL3.4 Tailored Loose Matches - MISSING
810 RL3.5 Tailored Ranges - MISSING
811 RL3.6 Context Matching - MISSING [19]
812 RL3.7 Incremental Matches - MISSING
813 ( RL3.8 Unicode Set Sharing )
814 RL3.9 Possible Match Sets - MISSING
815 RL3.10 Folded Matching - MISSING [20]
816 RL3.11 Submatchers - MISSING
817
818 [17] see UAX#10 "Unicode Collation Algorithms"
819 [18] have Unicode::Collate but not integrated to regexes
820 [19] have (?<=x) and (?=x), but look-aheads or look-behinds should see
821 outside of the target substring
822 [20] need insensitive matching for linguistic features other than case;
823 for example, hiragana to katakana, wide and narrow, simplified Han
824 to traditional Han (see UTR#30 "Character Foldings")
776f8809
JH
825
826=back
827
c349b1b9
JH
828=head2 Unicode Encodings
829
376d9008
JB
830Unicode characters are assigned to I<code points>, which are abstract
831numbers. To use these numbers, various encodings are needed.
c349b1b9
JH
832
833=over 4
834
c29a771d 835=item *
5cb3728c
RB
836
837UTF-8
c349b1b9 838
3e4dbfed 839UTF-8 is a variable-length (1 to 6 bytes, current character allocations
376d9008
JB
840require 4 bytes), byte-order independent encoding. For ASCII (and we
841really do mean 7-bit ASCII, not another 8-bit encoding), UTF-8 is
842transparent.
c349b1b9 843
8c007b5a 844The following table is from Unicode 3.2.
05632f9a
JH
845
846 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
847
8c007b5a
JH
848 U+0000..U+007F 00..7F
849 U+0080..U+07FF C2..DF 80..BF
ec90690f
TS
850 U+0800..U+0FFF E0 A0..BF 80..BF
851 U+1000..U+CFFF E1..EC 80..BF 80..BF
852 U+D000..U+D7FF ED 80..9F 80..BF
8c007b5a 853 U+D800..U+DFFF ******* ill-formed *******
ec90690f 854 U+E000..U+FFFF EE..EF 80..BF 80..BF
05632f9a
JH
855 U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
856 U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
857 U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
858
376d9008
JB
859Note the C<A0..BF> in C<U+0800..U+0FFF>, the C<80..9F> in
860C<U+D000...U+D7FF>, the C<90..B>F in C<U+10000..U+3FFFF>, and the
861C<80...8F> in C<U+100000..U+10FFFF>. The "gaps" are caused by legal
862UTF-8 avoiding non-shortest encodings: it is technically possible to
863UTF-8-encode a single code point in different ways, but that is
864explicitly forbidden, and the shortest possible encoding should always
865be used. So that's what Perl does.
37361303 866
376d9008 867Another way to look at it is via bits:
05632f9a
JH
868
869 Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
870
871 0aaaaaaa 0aaaaaaa
872 00000bbbbbaaaaaa 110bbbbb 10aaaaaa
873 ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
874 00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa
875
876As you can see, the continuation bytes all begin with C<10>, and the
8c007b5a 877leading bits of the start byte tell how many bytes the are in the
05632f9a
JH
878encoded character.
879
c29a771d 880=item *
5cb3728c
RB
881
882UTF-EBCDIC
dbe420b4 883
376d9008 884Like UTF-8 but EBCDIC-safe, in the way that UTF-8 is ASCII-safe.
dbe420b4 885
c29a771d 886=item *
5cb3728c 887
1e54db1a 888UTF-16, UTF-16BE, UTF-16LE, Surrogates, and BOMs (Byte Order Marks)
c349b1b9 889
1bfb14c4
JH
890The followings items are mostly for reference and general Unicode
891knowledge, Perl doesn't use these constructs internally.
dbe420b4 892
c349b1b9 893UTF-16 is a 2 or 4 byte encoding. The Unicode code points
1bfb14c4
JH
894C<U+0000..U+FFFF> are stored in a single 16-bit unit, and the code
895points C<U+10000..U+10FFFF> in two 16-bit units. The latter case is
c349b1b9
JH
896using I<surrogates>, the first 16-bit unit being the I<high
897surrogate>, and the second being the I<low surrogate>.
898
376d9008 899Surrogates are code points set aside to encode the C<U+10000..U+10FFFF>
c349b1b9 900range of Unicode code points in pairs of 16-bit units. The I<high
376d9008
JB
901surrogates> are the range C<U+D800..U+DBFF>, and the I<low surrogates>
902are the range C<U+DC00..U+DFFF>. The surrogate encoding is
c349b1b9
JH
903
904 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
905 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
906
907and the decoding is
908
1a3fa709 909 $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
c349b1b9 910
feda178f 911If you try to generate surrogates (for example by using chr()), you
376d9008
JB
912will get a warning if warnings are turned on, because those code
913points are not valid for a Unicode character.
9466bab6 914
376d9008 915Because of the 16-bitness, UTF-16 is byte-order dependent. UTF-16
c349b1b9 916itself can be used for in-memory computations, but if storage or
376d9008
JB
917transfer is required either UTF-16BE (big-endian) or UTF-16LE
918(little-endian) encodings must be chosen.
c349b1b9
JH
919
920This introduces another problem: what if you just know that your data
376d9008
JB
921is UTF-16, but you don't know which endianness? Byte Order Marks, or
922BOMs, are a solution to this. A special character has been reserved
86bbd6d1 923in Unicode to function as a byte order marker: the character with the
376d9008 924code point C<U+FEFF> is the BOM.
042da322 925
c349b1b9 926The trick is that if you read a BOM, you will know the byte order,
376d9008
JB
927since if it was written on a big-endian platform, you will read the
928bytes C<0xFE 0xFF>, but if it was written on a little-endian platform,
929you will read the bytes C<0xFF 0xFE>. (And if the originating platform
930was writing in UTF-8, you will read the bytes C<0xEF 0xBB 0xBF>.)
042da322 931
86bbd6d1 932The way this trick works is that the character with the code point
376d9008
JB
933C<U+FFFE> is guaranteed not to be a valid Unicode character, so the
934sequence of bytes C<0xFF 0xFE> is unambiguously "BOM, represented in
1bfb14c4 935little-endian format" and cannot be C<U+FFFE>, represented in big-endian
042da322 936format".
c349b1b9 937
c29a771d 938=item *
5cb3728c 939
1e54db1a 940UTF-32, UTF-32BE, UTF-32LE
c349b1b9
JH
941
942The UTF-32 family is pretty much like the UTF-16 family, expect that
042da322 943the units are 32-bit, and therefore the surrogate scheme is not
376d9008
JB
944needed. The BOM signatures will be C<0x00 0x00 0xFE 0xFF> for BE and
945C<0xFF 0xFE 0x00 0x00> for LE.
c349b1b9 946
c29a771d 947=item *
5cb3728c
RB
948
949UCS-2, UCS-4
c349b1b9 950
86bbd6d1 951Encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit
376d9008 952encoding. Unlike UTF-16, UCS-2 is not extensible beyond C<U+FFFF>,
339cfa0e
JH
953because it does not use surrogates. UCS-4 is a 32-bit encoding,
954functionally identical to UTF-32.
c349b1b9 955
c29a771d 956=item *
5cb3728c
RB
957
958UTF-7
c349b1b9 959
376d9008
JB
960A seven-bit safe (non-eight-bit) encoding, which is useful if the
961transport or storage is not eight-bit safe. Defined by RFC 2152.
c349b1b9 962
95a1a48b
JH
963=back
964
0d7c09bb
JH
965=head2 Security Implications of Unicode
966
967=over 4
968
969=item *
970
971Malformed UTF-8
bf0fa0b2
JH
972
973Unfortunately, the specification of UTF-8 leaves some room for
974interpretation of how many bytes of encoded output one should generate
376d9008
JB
975from one input Unicode character. Strictly speaking, the shortest
976possible sequence of UTF-8 bytes should be generated,
977because otherwise there is potential for an input buffer overflow at
feda178f 978the receiving end of a UTF-8 connection. Perl always generates the
376d9008
JB
979shortest length UTF-8, and with warnings on Perl will warn about
980non-shortest length UTF-8 along with other malformations, such as the
981surrogates, which are not real Unicode code points.
bf0fa0b2 982
0d7c09bb
JH
983=item *
984
985Regular expressions behave slightly differently between byte data and
376d9008
JB
986character (Unicode) data. For example, the "word character" character
987class C<\w> will work differently depending on if data is eight-bit bytes
988or Unicode.
0d7c09bb 989
376d9008
JB
990In the first case, the set of C<\w> characters is either small--the
991default set of alphabetic characters, digits, and the "_"--or, if you
0d7c09bb
JH
992are using a locale (see L<perllocale>), the C<\w> might contain a few
993more letters according to your language and country.
994
376d9008 995In the second case, the C<\w> set of characters is much, much larger.
1bfb14c4
JH
996Most importantly, even in the set of the first 256 characters, it will
997probably match different characters: unlike most locales, which are
998specific to a language and country pair, Unicode classifies all the
999characters that are letters I<somewhere> as C<\w>. For example, your
1000locale might not think that LATIN SMALL LETTER ETH is a letter (unless
1001you happen to speak Icelandic), but Unicode does.
0d7c09bb 1002
376d9008 1003As discussed elsewhere, Perl has one foot (two hooves?) planted in
1bfb14c4
JH
1004each of two worlds: the old world of bytes and the new world of
1005characters, upgrading from bytes to characters when necessary.
376d9008
JB
1006If your legacy code does not explicitly use Unicode, no automatic
1007switch-over to characters should happen. Characters shouldn't get
1bfb14c4
JH
1008downgraded to bytes, either. It is possible to accidentally mix bytes
1009and characters, however (see L<perluniintro>), in which case C<\w> in
1010regular expressions might start behaving differently. Review your
1011code. Use warnings and the C<strict> pragma.
0d7c09bb
JH
1012
1013=back
1014
c349b1b9
JH
1015=head2 Unicode in Perl on EBCDIC
1016
376d9008
JB
1017The way Unicode is handled on EBCDIC platforms is still
1018experimental. On such platforms, references to UTF-8 encoding in this
1019document and elsewhere should be read as meaning the UTF-EBCDIC
1020specified in Unicode Technical Report 16, unless ASCII vs. EBCDIC issues
c349b1b9 1021are specifically discussed. There is no C<utfebcdic> pragma or
376d9008 1022":utfebcdic" layer; rather, "utf8" and ":utf8" are reused to mean
86bbd6d1
PN
1023the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic>
1024for more discussion of the issues.
c349b1b9 1025
b310b053
JH
1026=head2 Locales
1027
4616122b 1028Usually locale settings and Unicode do not affect each other, but
b310b053
JH
1029there are a couple of exceptions:
1030
1031=over 4
1032
1033=item *
1034
8aa8f774
JH
1035You can enable automatic UTF-8-ification of your standard file
1036handles, default C<open()> layer, and C<@ARGV> by using either
1037the C<-C> command line switch or the C<PERL_UNICODE> environment
1038variable, see L<perlrun> for the documentation of the C<-C> switch.
b310b053
JH
1039
1040=item *
1041
376d9008
JB
1042Perl tries really hard to work both with Unicode and the old
1043byte-oriented world. Most often this is nice, but sometimes Perl's
1044straddling of the proverbial fence causes problems.
b310b053
JH
1045
1046=back
1047
1aad1664
JH
1048=head2 When Unicode Does Not Happen
1049
1050While Perl does have extensive ways to input and output in Unicode,
1051and few other 'entry points' like the @ARGV which can be interpreted
1052as Unicode (UTF-8), there still are many places where Unicode (in some
1053encoding or another) could be given as arguments or received as
1054results, or both, but it is not.
1055
6cd4dd6c
JH
1056The following are such interfaces. For all of these interfaces Perl
1057currently (as of 5.8.3) simply assumes byte strings both as arguments
1058and results, or UTF-8 strings if the C<encoding> pragma has been used.
1aad1664
JH
1059
1060One reason why Perl does not attempt to resolve the role of Unicode in
1061this cases is that the answers are highly dependent on the operating
1062system and the file system(s). For example, whether filenames can be
1063in Unicode, and in exactly what kind of encoding, is not exactly a
1064portable concept. Similarly for the qx and system: how well will the
1065'command line interface' (and which of them?) handle Unicode?
1066
1067=over 4
1068
557a2462
RB
1069=item *
1070
51f494cc 1071chdir, chmod, chown, chroot, exec, link, lstat, mkdir,
1e8e8236 1072rename, rmdir, stat, symlink, truncate, unlink, utime, -X
557a2462
RB
1073
1074=item *
1075
1076%ENV
1077
1078=item *
1079
1080glob (aka the <*>)
1081
1082=item *
1aad1664 1083
557a2462 1084open, opendir, sysopen
1aad1664 1085
557a2462 1086=item *
1aad1664 1087
557a2462 1088qx (aka the backtick operator), system
1aad1664 1089
557a2462 1090=item *
1aad1664 1091
557a2462 1092readdir, readlink
1aad1664
JH
1093
1094=back
1095
1096=head2 Forcing Unicode in Perl (Or Unforcing Unicode in Perl)
1097
1098Sometimes (see L</"When Unicode Does Not Happen">) there are
2bbc8d55
SP
1099situations where you simply need to force a byte
1100string into UTF-8, or vice versa. The low-level calls
1101utf8::upgrade($bytestring) and utf8::downgrade($utf8string[, FAIL_OK]) are
1aad1664
JH
1102the answers.
1103
2bbc8d55
SP
1104Note that utf8::downgrade() can fail if the string contains characters
1105that don't fit into a byte.
1aad1664 1106
95a1a48b
JH
1107=head2 Using Unicode in XS
1108
3a2263fe
RGS
1109If you want to handle Perl Unicode in XS extensions, you may find the
1110following C APIs useful. See also L<perlguts/"Unicode Support"> for an
1111explanation about Unicode at the XS level, and L<perlapi> for the API
1112details.
95a1a48b
JH
1113
1114=over 4
1115
1116=item *
1117
1bfb14c4 1118C<DO_UTF8(sv)> returns true if the C<UTF8> flag is on and the bytes
2bbc8d55 1119pragma is not in effect. C<SvUTF8(sv)> returns true if the C<UTF8>
1bfb14c4
JH
1120flag is on; the bytes pragma is ignored. The C<UTF8> flag being on
1121does B<not> mean that there are any characters of code points greater
1122than 255 (or 127) in the scalar or that there are even any characters
1123in the scalar. What the C<UTF8> flag means is that the sequence of
1124octets in the representation of the scalar is the sequence of UTF-8
1125encoded code points of the characters of a string. The C<UTF8> flag
1126being off means that each octet in this representation encodes a
1127single character with code point 0..255 within the string. Perl's
1128Unicode model is not to use UTF-8 until it is absolutely necessary.
95a1a48b
JH
1129
1130=item *
1131
2bbc8d55 1132C<uvchr_to_utf8(buf, chr)> writes a Unicode character code point into
1bfb14c4 1133a buffer encoding the code point as UTF-8, and returns a pointer
2bbc8d55 1134pointing after the UTF-8 bytes. It works appropriately on EBCDIC machines.
95a1a48b
JH
1135
1136=item *
1137
2bbc8d55 1138C<utf8_to_uvchr(buf, lenp)> reads UTF-8 encoded bytes from a buffer and
376d9008 1139returns the Unicode character code point and, optionally, the length of
2bbc8d55 1140the UTF-8 byte sequence. It works appropriately on EBCDIC machines.
95a1a48b
JH
1141
1142=item *
1143
376d9008
JB
1144C<utf8_length(start, end)> returns the length of the UTF-8 encoded buffer
1145in characters. C<sv_len_utf8(sv)> returns the length of the UTF-8 encoded
95a1a48b
JH
1146scalar.
1147
1148=item *
1149
376d9008
JB
1150C<sv_utf8_upgrade(sv)> converts the string of the scalar to its UTF-8
1151encoded form. C<sv_utf8_downgrade(sv)> does the opposite, if
1152possible. C<sv_utf8_encode(sv)> is like sv_utf8_upgrade except that
1153it does not set the C<UTF8> flag. C<sv_utf8_decode()> does the
1154opposite of C<sv_utf8_encode()>. Note that none of these are to be
1155used as general-purpose encoding or decoding interfaces: C<use Encode>
1156for that. C<sv_utf8_upgrade()> is affected by the encoding pragma
1157but C<sv_utf8_downgrade()> is not (since the encoding pragma is
1158designed to be a one-way street).
95a1a48b
JH
1159
1160=item *
1161
376d9008 1162C<is_utf8_char(s)> returns true if the pointer points to a valid UTF-8
90f968e0 1163character.
95a1a48b
JH
1164
1165=item *
1166
376d9008 1167C<is_utf8_string(buf, len)> returns true if C<len> bytes of the buffer
95a1a48b
JH
1168are valid UTF-8.
1169
1170=item *
1171
376d9008
JB
1172C<UTF8SKIP(buf)> will return the number of bytes in the UTF-8 encoded
1173character in the buffer. C<UNISKIP(chr)> will return the number of bytes
1174required to UTF-8-encode the Unicode character code point. C<UTF8SKIP()>
90f968e0 1175is useful for example for iterating over the characters of a UTF-8
376d9008 1176encoded buffer; C<UNISKIP()> is useful, for example, in computing
90f968e0 1177the size required for a UTF-8 encoded buffer.
95a1a48b
JH
1178
1179=item *
1180
376d9008 1181C<utf8_distance(a, b)> will tell the distance in characters between the
95a1a48b
JH
1182two pointers pointing to the same UTF-8 encoded buffer.
1183
1184=item *
1185
2bbc8d55 1186C<utf8_hop(s, off)> will return a pointer to a UTF-8 encoded buffer
376d9008
JB
1187that is C<off> (positive or negative) Unicode characters displaced
1188from the UTF-8 buffer C<s>. Be careful not to overstep the buffer:
1189C<utf8_hop()> will merrily run off the end or the beginning of the
1190buffer if told to do so.
95a1a48b 1191
d2cc3551
JH
1192=item *
1193
376d9008
JB
1194C<pv_uni_display(dsv, spv, len, pvlim, flags)> and
1195C<sv_uni_display(dsv, ssv, pvlim, flags)> are useful for debugging the
1196output of Unicode strings and scalars. By default they are useful
1197only for debugging--they display B<all> characters as hexadecimal code
1bfb14c4
JH
1198points--but with the flags C<UNI_DISPLAY_ISPRINT>,
1199C<UNI_DISPLAY_BACKSLASH>, and C<UNI_DISPLAY_QQ> you can make the
1200output more readable.
d2cc3551
JH
1201
1202=item *
1203
2bbc8d55 1204C<ibcmp_utf8(s1, pe1, l1, u1, s2, pe2, l2, u2)> can be used to
376d9008
JB
1205compare two strings case-insensitively in Unicode. For case-sensitive
1206comparisons you can just use C<memEQ()> and C<memNE()> as usual.
d2cc3551 1207
c349b1b9
JH
1208=back
1209
95a1a48b
JH
1210For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h>
1211in the Perl source code distribution.
1212
c29a771d
JH
1213=head1 BUGS
1214
376d9008 1215=head2 Interaction with Locales
7eabb34d 1216
376d9008
JB
1217Use of locales with Unicode data may lead to odd results. Currently,
1218Perl attempts to attach 8-bit locale info to characters in the range
12190..255, but this technique is demonstrably incorrect for locales that
1220use characters above that range when mapped into Unicode. Perl's
1221Unicode support will also tend to run slower. Use of locales with
1222Unicode is discouraged.
c29a771d 1223
2bbc8d55
SP
1224=head2 Problems with characters whose ordinal numbers are in the range 128 - 255 with no Locale specified
1225
1226Without a locale specified, unlike all other characters or code points,
1227these characters have very different semantics in byte semantics versus
1228character semantics.
1229In character semantics they are interpreted as Unicode code points, which means
1230they are viewed as Latin-1 (ISO-8859-1).
1231In byte semantics, they are considered to be unassigned characters,
1232meaning that the only semantics they have is their
1233ordinal numbers, and that they are not members of various character classes.
1234None are considered to match C<\w> for example, but all match C<\W>.
1235Besides these class matches,
1236the known operations that this affects are those that change the case,
1237regular expression matching while ignoring case,
1238and B<quotemeta()>.
1239This can lead to unexpected results in which a string's semantics suddenly
1240change if a code point above 255 is appended to or removed from it,
1241which changes the string's semantics from byte to character or vice versa.
1242This behavior is scheduled to change in version 5.12, but in the meantime,
fe749c9a
KW
1243a workaround is to always call utf8::upgrade($string), or to use the
1244standard modules L<Encode> or L<charnames>.
2bbc8d55 1245
376d9008 1246=head2 Interaction with Extensions
7eabb34d 1247
376d9008 1248When Perl exchanges data with an extension, the extension should be
2575c402 1249able to understand the UTF8 flag and act accordingly. If the
376d9008
JB
1250extension doesn't know about the flag, it's likely that the extension
1251will return incorrectly-flagged data.
7eabb34d
A
1252
1253So if you're working with Unicode data, consult the documentation of
1254every module you're using if there are any issues with Unicode data
1255exchange. If the documentation does not talk about Unicode at all,
a73d23f6 1256suspect the worst and probably look at the source to learn how the
376d9008 1257module is implemented. Modules written completely in Perl shouldn't
a73d23f6
RGS
1258cause problems. Modules that directly or indirectly access code written
1259in other programming languages are at risk.
7eabb34d 1260
376d9008 1261For affected functions, the simple strategy to avoid data corruption is
7eabb34d 1262to always make the encoding of the exchanged data explicit. Choose an
376d9008 1263encoding that you know the extension can handle. Convert arguments passed
7eabb34d
A
1264to the extensions to that encoding and convert results back from that
1265encoding. Write wrapper functions that do the conversions for you, so
1266you can later change the functions when the extension catches up.
1267
376d9008 1268To provide an example, let's say the popular Foo::Bar::escape_html
7eabb34d
A
1269function doesn't deal with Unicode data yet. The wrapper function
1270would convert the argument to raw UTF-8 and convert the result back to
376d9008 1271Perl's internal representation like so:
7eabb34d
A
1272
1273 sub my_escape_html ($) {
1274 my($what) = shift;
1275 return unless defined $what;
1276 Encode::decode_utf8(Foo::Bar::escape_html(Encode::encode_utf8($what)));
1277 }
1278
1279Sometimes, when the extension does not convert data but just stores
1280and retrieves them, you will be in a position to use the otherwise
1281dangerous Encode::_utf8_on() function. Let's say the popular
66b79f27 1282C<Foo::Bar> extension, written in C, provides a C<param> method that
7eabb34d
A
1283lets you store and retrieve data according to these prototypes:
1284
1285 $self->param($name, $value); # set a scalar
1286 $value = $self->param($name); # retrieve a scalar
1287
1288If it does not yet provide support for any encoding, one could write a
1289derived class with such a C<param> method:
1290
1291 sub param {
1292 my($self,$name,$value) = @_;
1293 utf8::upgrade($name); # make sure it is UTF-8 encoded
af55fc6a 1294 if (defined $value) {
7eabb34d
A
1295 utf8::upgrade($value); # make sure it is UTF-8 encoded
1296 return $self->SUPER::param($name,$value);
1297 } else {
1298 my $ret = $self->SUPER::param($name);
1299 Encode::_utf8_on($ret); # we know, it is UTF-8 encoded
1300 return $ret;
1301 }
1302 }
1303
a73d23f6
RGS
1304Some extensions provide filters on data entry/exit points, such as
1305DB_File::filter_store_key and family. Look out for such filters in
66b79f27 1306the documentation of your extensions, they can make the transition to
7eabb34d
A
1307Unicode data much easier.
1308
376d9008 1309=head2 Speed
7eabb34d 1310
c29a771d 1311Some functions are slower when working on UTF-8 encoded strings than
574c8022 1312on byte encoded strings. All functions that need to hop over
7c17141f
JH
1313characters such as length(), substr() or index(), or matching regular
1314expressions can work B<much> faster when the underlying data are
1315byte-encoded.
1316
1317In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1
1318a caching scheme was introduced which will hopefully make the slowness
a104b433
JH
1319somewhat less spectacular, at least for some operations. In general,
1320operations with UTF-8 encoded strings are still slower. As an example,
1321the Unicode properties (character classes) like C<\p{Nd}> are known to
1322be quite a bit slower (5-20 times) than their simpler counterparts
1323like C<\d> (then again, there 268 Unicode characters matching C<Nd>
1324compared with the 10 ASCII characters matching C<d>).
666f95b9 1325
fe749c9a
KW
1326=head2 Possible problems on EBCDIC platforms
1327
1328In earlier versions, when byte and character data were concatenated,
1329the new string was sometimes created by
1330decoding the byte strings as I<ISO 8859-1 (Latin-1)>, even if the
1331old Unicode string used EBCDIC.
1332
1333If you find any of these, please report them as bugs.
1334
c8d992ba
A
1335=head2 Porting code from perl-5.6.X
1336
1337Perl 5.8 has a different Unicode model from 5.6. In 5.6 the programmer
1338was required to use the C<utf8> pragma to declare that a given scope
1339expected to deal with Unicode data and had to make sure that only
1340Unicode data were reaching that scope. If you have code that is
1341working with 5.6, you will need some of the following adjustments to
1342your code. The examples are written such that the code will continue
1343to work under 5.6, so you should be safe to try them out.
1344
1345=over 4
1346
1347=item *
1348
1349A filehandle that should read or write UTF-8
1350
1351 if ($] > 5.007) {
740d4bb2 1352 binmode $fh, ":encoding(utf8)";
c8d992ba
A
1353 }
1354
1355=item *
1356
1357A scalar that is going to be passed to some extension
1358
1359Be it Compress::Zlib, Apache::Request or any extension that has no
1360mention of Unicode in the manpage, you need to make sure that the
2575c402 1361UTF8 flag is stripped off. Note that at the time of this writing
c8d992ba
A
1362(October 2002) the mentioned modules are not UTF-8-aware. Please
1363check the documentation to verify if this is still true.
1364
1365 if ($] > 5.007) {
1366 require Encode;
1367 $val = Encode::encode_utf8($val); # make octets
1368 }
1369
1370=item *
1371
1372A scalar we got back from an extension
1373
1374If you believe the scalar comes back as UTF-8, you will most likely
2575c402 1375want the UTF8 flag restored:
c8d992ba
A
1376
1377 if ($] > 5.007) {
1378 require Encode;
1379 $val = Encode::decode_utf8($val);
1380 }
1381
1382=item *
1383
1384Same thing, if you are really sure it is UTF-8
1385
1386 if ($] > 5.007) {
1387 require Encode;
1388 Encode::_utf8_on($val);
1389 }
1390
1391=item *
1392
1393A wrapper for fetchrow_array and fetchrow_hashref
1394
1395When the database contains only UTF-8, a wrapper function or method is
1396a convenient way to replace all your fetchrow_array and
1397fetchrow_hashref calls. A wrapper function will also make it easier to
1398adapt to future enhancements in your database driver. Note that at the
1399time of this writing (October 2002), the DBI has no standardized way
1400to deal with UTF-8 data. Please check the documentation to verify if
1401that is still true.
1402
1403 sub fetchrow {
1404 my($self, $sth, $what) = @_; # $what is one of fetchrow_{array,hashref}
1405 if ($] < 5.007) {
1406 return $sth->$what;
1407 } else {
1408 require Encode;
1409 if (wantarray) {
1410 my @arr = $sth->$what;
1411 for (@arr) {
1412 defined && /[^\000-\177]/ && Encode::_utf8_on($_);
1413 }
1414 return @arr;
1415 } else {
1416 my $ret = $sth->$what;
1417 if (ref $ret) {
1418 for my $k (keys %$ret) {
1419 defined && /[^\000-\177]/ && Encode::_utf8_on($_) for $ret->{$k};
1420 }
1421 return $ret;
1422 } else {
1423 defined && /[^\000-\177]/ && Encode::_utf8_on($_) for $ret;
1424 return $ret;
1425 }
1426 }
1427 }
1428 }
1429
1430
1431=item *
1432
1433A large scalar that you know can only contain ASCII
1434
1435Scalars that contain only ASCII and are marked as UTF-8 are sometimes
1436a drag to your program. If you recognize such a situation, just remove
2575c402 1437the UTF8 flag:
c8d992ba
A
1438
1439 utf8::downgrade($val) if $] > 5.007;
1440
1441=back
1442
51f494cc
KW
1443=head2 Hacking Perl to work on earlier Unicode versions (for very serious hackers only)
1444
1445Perl by default comes with the latest supported Unicode version built in, but
1446you can change to use any earlier one.
1447
1448Download the files in the version of Unicode that you want from the Unicode web
1449site L<http://www.unicode.org>). These should replace the existing files in
1450C<\$Config{privlib}>/F<unicore>. (C<\%Config> is available from the Config
1451module.) Follow the instructions in F<README.perl> in that directory to change
1452some of their names, and then run F<make>.
1453
1454It is even possible to download them to a different directory, and then change
1455F<utf8_heavy.pl> in the directory C<\$Config{privlib}> to point to the new
1456directory, or maybe make a copy of that directory before making the change, and
1457using C<@INC> or the C<-I> run-time flag to switch between versions at will,
1458but all this is beyond the scope of these instructions.
1459
393fec97
GS
1460=head1 SEE ALSO
1461
51f494cc 1462L<perlunitut>, L<perluniintro>, L<perluniprops>, L<Encode>, L<open>, L<utf8>, L<bytes>,
a05d7ebb 1463L<perlretut>, L<perlvar/"${^UNICODE}">
51f494cc 1464L<http://www.unicode.org/reports/tr44>).
393fec97
GS
1465
1466=cut