In perl.git, the branch blead has been updated <http://perl5.git.perl.org/perl.git/commitdiff/737f753477826d5b8aea4125965e48c81d274b7d?hp=ca2bf4b7509cb12126c80f55c7b9f389abd717aa>
- Log ----------------------------------------------------------------- commit 737f753477826d5b8aea4125965e48c81d274b7d Author: Karl Williamson <[email protected]> Date: Thu May 7 17:09:18 2015 -0600 perlop: Don't use bitwise string ops on UTF-8 The behavior is likely to change M pod/perlop.pod commit 9f1b81728560769e0961fb63e5506fd139dd0ee8 Author: Karl Williamson <[email protected]> Date: Thu May 7 17:08:30 2015 -0600 perlop: Make correction This recipe has the same result under both EBCDIC and ASCII M pod/perlop.pod commit 6e31cdd1306e50af630ec6ef415b48d1ad6c978d Author: Karl Williamson <[email protected]> Date: Thu May 7 17:07:16 2015 -0600 perlguts: Add links to perlunicode M pod/perlguts.pod commit a6a7eedc7e11636c834ac840a3a04d5d2931932a Author: Karl Williamson <[email protected]> Date: Thu May 7 16:58:51 2015 -0600 perlunicode: Revamp I've always had problems understanding the point of some of the discussion of this pod, so I've finally rewritten parts to bring it up-to-date with modern Unicode support and clarify things. In particular the "byte" vs "character" semantics didn't make sense to me. Perl has always used character semantics (outside of a few places noted in both pod versions); it's just that the advent of Unicode made 'byte' and 'character' no longer synonymous. So I've split that section of the old pod, with the added section entitled "ASCII rules vs Unicode rules", which I think is more clear. M pod/perlunicode.pod commit b65e6125f8ebcc9dee91ee06a6b3fcd88cde6f4b Author: Karl Williamson <[email protected]> Date: Thu May 7 16:53:34 2015 -0600 perlunicode: Nits, minor fixes M pod/perlunicode.pod commit 74fe8880c4667610a3b0aa9e8167fe1b407dc5c5 Author: Karl Williamson <[email protected]> Date: Thu May 7 13:00:00 2015 -0600 perluniintro: Add note Unicode ranges don't currently work in tr/// M pod/perluniintro.pod commit da0c31fa675d6f65c10f0b06995808926e429008 Author: Karl Williamson <[email protected]> Date: Thu May 7 12:56:50 2015 -0600 perlunitut: Add note M pod/perlunitut.pod commit 60949ddd808da1e671f6222e6dc6efebfcb77ece Author: Karl Williamson <[email protected]> Date: Thu May 7 12:54:32 2015 -0600 perlrun: Note existence of -DL M pod/perlrun.pod commit 268e690504dd7c01f8946eee54865856e54cb871 Author: Karl Williamson <[email protected]> Date: Thu May 7 12:53:45 2015 -0600 perlrebackslash: Note \b{sb} is subject to change The Unicode algorithm has big issues, and may change. M pod/perlrebackslash.pod commit 7a1453700ba68b31e16804be4b8ba731d3cccb6c Author: Karl Williamson <[email protected]> Date: Thu May 7 12:48:22 2015 -0600 perlebcdic: Move text from perlunicode This consolidates the EBCDIC problems into one place M pod/perlebcdic.pod M pod/perlunicode.pod commit 89d7b922fee7860d558cfc609e41434b49c264f4 Author: Karl Williamson <[email protected]> Date: Thu May 7 10:58:02 2015 -0600 perlapi: Clearer wording in intro M autodoc.pl commit 8cca77bcd5a95ede9ee09d709dc6b908b152efae Author: Karl Williamson <[email protected]> Date: Wed May 6 21:10:39 2015 -0600 perlapi: Add intro text to Unicode section M utf8.h commit 37b3b6086552e04f105d3f09b6fdef16cc6a4a64 Author: Karl Williamson <[email protected]> Date: Wed May 6 21:07:33 2015 -0600 perlunicode: Refer to perlguts for XS handling Don't redescribe things here. Also refer to perlapi. M pod/perlunicode.pod commit 6db25795da554240a8df760c2cd8babd61b1622b Author: Karl Williamson <[email protected]> Date: Wed May 6 21:05:19 2015 -0600 perlguts: Add/update text about handling Unicode M pod/perlguts.pod commit 3ad86f0e0596b296a94a80003107328f692c8219 Author: Karl Williamson <[email protected]> Date: Wed May 6 21:02:16 2015 -0600 perlguts: Add EBCDIC info M pod/perlguts.pod commit 61ad4b941643c11b80309e30eab01446ad239acc Author: Karl Williamson <[email protected]> Date: Wed May 6 21:01:32 2015 -0600 perlguts: Nits, corrections and clarifications M pod/perlguts.pod commit bd18bd400813bdd63c4212b321b8876f2ea01818 Author: Karl Williamson <[email protected]> Date: Wed May 6 20:42:15 2015 -0600 perlapi: Document some functions These are mentioned in some other pods. It's best to bring them into perlapi, and refer to them from the other pods. M handy.h M utf8.h commit 2accb712600a36336d0544f369bc2a30ee70bdf3 Author: Karl Williamson <[email protected]> Date: Wed May 6 20:47:15 2015 -0600 utf8.h: Add a #define The name UVCHR... parallels the usage of various functions uvchr... It's less confusing to keep the same name form for the same type of functionality M utf8.h ----------------------------------------------------------------------- Summary of changes: autodoc.pl | 4 +- handy.h | 10 + pod/perlebcdic.pod | 7 + pod/perlguts.pod | 123 +++-- pod/perlop.pod | 6 +- pod/perlrebackslash.pod | 3 +- pod/perlrun.pod | 2 + pod/perlunicode.pod | 1210 +++++++++++++++++++++++------------------------ pod/perluniintro.pod | 7 +- pod/perlunitut.pod | 3 +- utf8.h | 43 +- 11 files changed, 763 insertions(+), 655 deletions(-) diff --git a/autodoc.pl b/autodoc.pl index 9395d91..b27fc4d 100644 --- a/autodoc.pl +++ b/autodoc.pl @@ -404,8 +404,8 @@ whose ordinal numbers are in the range 0 - 127). And documentation and comments may still use the term ASCII, when sometimes in fact the entire range from 0 - 255 is meant. -Note that Perl can be compiled and run under EBCDIC (See L<perlebcdic>) -or ASCII. Most of the documentation (and even comments in the code) +Note that Perl can be compiled and run under either ASCII or EBCDIC (See +L<perlebcdic>). Most of the documentation (and even comments in the code) ignore the EBCDIC possibility. For almost all purposes the differences are transparent. As an example, under EBCDIC, diff --git a/handy.h b/handy.h index 89055c5..3e6fd52 100644 --- a/handy.h +++ b/handy.h @@ -449,6 +449,16 @@ Test two strings to see if they are equal. The C<len> parameter indicates the number of bytes to compare. Returns true or false. (A wrapper for C<strncmp>). +=for apidoc Am|bool|memEQ|char* s1|char* s2|STRLEN len +Test two buffers (which may contain embedded C<NUL> characters, to see if they +are equal. The C<len> parameter indicates the number of bytes to compare. +Returns zero if equal, or non-zero if non-equal. + +=for apidoc Am|bool|memNE|char* s1|char* s2|STRLEN len +Test two buffers (which may contain embedded C<NUL> characters, to see if they +are not equal. The C<len> parameter indicates the number of bytes to compare. +Returns zero if non-equal, or non-zero if equal. + =cut */ diff --git a/pod/perlebcdic.pod b/pod/perlebcdic.pod index 1962f92..c1d8c85 100644 --- a/pod/perlebcdic.pod +++ b/pod/perlebcdic.pod @@ -1867,6 +1867,13 @@ L<Unicode::Normalize> are not supported under EBCDIC; likewise for the L<Encode> partially works. +=item * + +In earlier versions, when byte and character data were concatenated, +the new string was sometimes created by +decoding the byte strings as I<ISO 8859-1 (Latin-1)>, even if the +old Unicode string used EBCDIC. + =back =head1 SEE ALSO diff --git a/pod/perlguts.pod b/pod/perlguts.pod index 27f7540..a58d7ad 100644 --- a/pod/perlguts.pod +++ b/pod/perlguts.pod @@ -1365,7 +1365,7 @@ aware that the behavior may change in the future, umm, without warning. The perl tie function associates a variable with an object that implements the various GET, SET, etc methods. To perform the equivalent of the perl tie function from an XSUB, you must mimic this behaviour. The code below -carries out the necessary steps - firstly it creates a new hash, and then +carries out the necessary steps -- firstly it creates a new hash, and then creates a second hash which it blesses into the class which will implement the tie methods. Lastly it ties the two hashes together, and returns a reference to the new tied hash. Note that the code below does NOT call the @@ -2729,7 +2729,7 @@ macros is faster than using C<call_*>. =head2 Source Documentation There's an effort going on to document the internal functions and -automatically produce reference manuals from them - L<perlapi> is one +automatically produce reference manuals from them -- L<perlapi> is one such manual which details all the functions which are available to XS writers. L<perlintern> is the autogenerated manual for the functions which are not part of the API and are supposedly for internal use only. @@ -2800,20 +2800,27 @@ characters, and the one Perl uses is called UTF-8. UTF-8 uses a variable number of bytes to represent a character. You can learn more about Unicode and Perl's Unicode model in L<perlunicode>. +(On EBCDIC platforms, Perl uses instead UTF-EBCDIC, which is a form of +UTF-8 adapted for EBCDIC platforms. Below, we just talk about UTF-8. +UTF-EBCDIC is like UTF-8, but the details are different. The macros +hide the differences from you, just remember that the particular numbers +and bit patterns presented below will differ in UTF-EBCDIC.) + =head2 How can I recognise a UTF-8 string? You can't. This is because UTF-8 data is stored in bytes just like non-UTF-8 data. The Unicode character 200, (C<0xC8> for you hex types) capital E with a grave accent, is represented by the two bytes C<v196.172>. Unfortunately, the non-Unicode string C<chr(196).chr(172)> -has that byte sequence as well. So you can't tell just by looking - this +has that byte sequence as well. So you can't tell just by looking -- this is what makes Unicode input an interesting problem. In general, you either have to know what you're dealing with, or you have to guess. The API function C<is_utf8_string> can help; it'll tell -you if a string contains only valid UTF-8 characters. However, it can't -do the work for you. On a character-by-character basis, -C<isUTF8_CHAR> +you if a string contains only valid UTF-8 characters, and the chances +of a non-UTF-8 string looking like valid UTF-8 become very small very +quickly with increasing string length. On a character-by-character +basis, C<isUTF8_CHAR> will tell you whether the current character in a string is valid UTF-8. =head2 How does UTF-8 represent Unicode characters? @@ -2823,8 +2830,9 @@ character. Characters with values 0...127 are stored in one byte, just like good ol' ASCII. Character 128 is stored as C<v194.128>; this continues up to character 191, which is C<v194.191>. Now we've run out of bits (191 is binary -C<10111111>) so we move on; 192 is C<v195.128>. And +C<10111111>) so we move on; character 192 is C<v195.128>. And so it goes on, moving to three bytes at character 2048. +L<perlunicode/Unicode Encodings> has pictures of how this works. Assuming you know you're dealing with a UTF-8 string, you can find out how long the first character in it is with the C<UTF8SKIP> macro: @@ -2843,7 +2851,7 @@ lightly. All bytes in a multi-byte UTF-8 character will have the high bit set, so you can test if you need to do something special with this -character like this (the UTF8_IS_INVARIANT() is a macro that tests +character like this (the C<UTF8_IS_INVARIANT()> is a macro that tests whether the byte is encoded as a single byte even in UTF-8): U8 *utf; @@ -2862,7 +2870,7 @@ You can also see in that example that we use C<utf8_to_uvchr_buf> to get the value of the character; the inverse function C<uvchr_to_utf8> is available for putting a UV into UTF-8: - if (!UTF8_IS_INVARIANT(uv)) + if (!UVCHR_IS_INVARIANT(uv)) /* Must treat this as UTF8 */ utf8 = uvchr_to_utf8(utf8, uv); else @@ -2877,16 +2885,19 @@ for instance, if your UTF-8 string contains C<v196.172>, and you skip that character, you can never match a C<chr(200)> in a non-UTF-8 string. So don't do that! +(Note that we don't have to test for invariant characters in the +examples above. The functions work on any well-formed UTF-8 input. +It's just that its faster to avoid the function overhead when it's not +needed.) + =head2 How does Perl store UTF-8 strings? -Currently, Perl deals with Unicode strings and non-Unicode strings +Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly differently. A flag in the SV, C<SVf_UTF8>, indicates that the string is internally encoded as UTF-8. Without it, the byte value is the -codepoint number and vice versa (in other words, the string is encoded -as iso-8859-1, but C<use feature 'unicode_strings'> is needed to get iso-8859-1 -semantics). This flag is only meaningful if the SV is C<SvPOK> -or immediately after stringification via C<SvPV> or a similar -macro. You can check and manipulate this flag with the +codepoint number and vice versa. This flag is only meaningful if the SV +is C<SvPOK> or immediately after stringification via C<SvPV> or a +similar macro. You can check and manipulate this flag with the following macros: SvUTF8(sv) @@ -2894,16 +2905,16 @@ following macros: SvUTF8_off(sv) This flag has an important effect on Perl's treatment of the string: if -Unicode data is not properly distinguished, regular expressions, +UTF-8 data is not properly distinguished, regular expressions, C<length>, C<substr> and other string handling operations will have -undesirable results. +undesirable (wrong) results. The problem comes when you have, for instance, a string that isn't -flagged as UTF-8, and contains a byte sequence that could be UTF-8 - +flagged as UTF-8, and contains a byte sequence that could be UTF-8 -- especially when combining non-UTF-8 and UTF-8 strings. -Never forget that the C<SVf_UTF8> flag is separate to the PV value; you -need be sure you don't accidentally knock it off while you're +Never forget that the C<SVf_UTF8> flag is separate from the PV value; you +need to be sure you don't accidentally knock it off while you're manipulating SVs. More specifically, you cannot expect to do this: SV *sv; @@ -2921,23 +2932,44 @@ old SV has the UTF8 flag set (I<after> the C<SvPV> call), and act accordingly: p = SvPV(sv, len); - frobnicate(p); + is_utf8 = SvUTF8(sv); + frobnicate(p, is_utf8); nsv = newSVpvn(p, len); - if (SvUTF8(sv)) + if (is_utf8) SvUTF8_on(nsv); -In fact, your C<frobnicate> function should be made aware of whether or -not it's dealing with UTF-8 data, so that it can handle the string -appropriately. +In the above, your C<frobnicate> function has been changed to be made +aware of whether or not it's dealing with UTF-8 data, so that it can +handle the string appropriately. Since just passing an SV to an XS function and copying the data of the SV is not enough to copy the UTF8 flags, even less right is just -passing a C<char *> to an XS function. +passing a S<C<char *>> to an XS function. + +For full generality, use the L<perlapi/DO_UTF8> macro to see if the +string in an SV is to be I<treated> as UTF-8. This takes into account +if the call to the XS function is being made from within the scope of +L<S<C<use bytes>>|bytes>. If so, the underlying bytes that comprise the +UTF-8 string are to be exposed, rather than the character they +represent. But this pragma should only really be used for debugging and +perhaps low-level testing at the byte level. Hence most XS code need +not concern itself with this, but various areas of the perl core do need +to support it. + +And this isn't the whole story. Starting in Perl v5.12, strings that +aren't encoded in UTF-8 may also be treated as Unicode under various +conditions (see L<perlunicode/ASCII Rules versus Unicode Rules>). +This is only really a problem for characters whose ordinals are between +128 and 255, and their behavior varies under ASCII versus Unicode rules +in ways that your code cares about (see L<perlunicode/The "Unicode Bug">). +There is no published API for dealing with this, as it is subject to +change, but you can look at the code for C<pp_lc> in F<pp.c> for an +example as to how it's currently done. =head2 How do I convert a string to UTF-8? If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade -one of the strings to UTF-8. If you've got an SV, the easiest way to do +the non-UTF-8 strings to UTF-8. If you've got an SV, the easiest way to do this is: sv_utf8_upgrade(sv); @@ -2958,6 +2990,21 @@ C<utf8_to_bytes> to go the other way, but naturally, this will fail if the string contains any characters above 255 that can't be represented in a single byte. +=head2 How do I compare strings? + +L<perlapi/sv_cmp> and L<perlapi/sv_cmp_flags> do a lexigraphic +comparison of two SV's, and handle UTF-8ness properly. Note, however, +that Unicode specifies a much fancier mechanism for collation, available +via the L<Unicode::Collate> module. + +To just compare two strings for equality/non-equality, you can just use +L<C<memEQ()>|perlapi/memEQ> and L<C<memNE()>|perlapi/memEQ> as usual, +except the strings must be both UTF-8 or not UTF-8 encoded. + +To compare two strings case-insensitively, use +L<C<foldEQ_utf8()>|perlapi/foldEQ_utf8> (the strings don't have to have +the same UTF-8ness). + =head2 Is there anything else I need to know? Not really. Just remember these things: @@ -2966,11 +3013,15 @@ Not really. Just remember these things: =item * -There's no way to tell if a string is UTF-8 or not. You can tell if an SV -is UTF-8 by looking at its C<SvUTF8> flag after stringifying it -with C<SvPV> or a similar macro. Don't forget to set the flag if -something should be UTF-8. Treat the flag as part of the PV, even though -it's not - if you pass on the PV to somewhere, pass on the flag too. +There's no way to tell if a S<C<char *>> or S<C<U8 *>> string is UTF-8 +or not. But you can tell if an SV is to be treated as UTF-8 by calling +C<DO_UTF8> on it, after stringifying it with C<SvPV> or a similar +macro. And, you can tell if SV is actually UTF-8 (even if it is not to +be treated as such) by looking at its C<SvUTF8> flag (again after +stringifying it). Don't forget to set the flag if something should be +UTF-8. +Treat the flag as part of the PV, even though it's not -- if you pass on +the PV to somewhere, pass on the flag too. =item * @@ -2979,8 +3030,8 @@ unless C<UTF8_IS_INVARIANT(*s)> in which case you can use C<*s>. =item * -When writing a character C<uv> to a UTF-8 string, B<always> use -C<uvchr_to_utf8>, unless C<UTF8_IS_INVARIANT(uv))> in which case +When writing a character UV to a UTF-8 string, B<always> use +C<uvchr_to_utf8>, unless C<UVCHR_IS_INVARIANT(uv))> in which case you can use C<*s = uv>. =item * @@ -3003,8 +3054,8 @@ C<gvsv, gvsv, add>.) This feature is implemented as a new op type, C<OP_CUSTOM>. The Perl core does not "know" anything special about this op type, and so it will not be involved in any optimizations. This also means that you can -define your custom ops to be any op structure - unary, binary, list and -so on - you like. +define your custom ops to be any op structure -- unary, binary, list and +so on -- you like. It's important to know what custom operators won't do for you. They won't let you add new syntax to Perl, directly. They won't even let you diff --git a/pod/perlop.pod b/pod/perlop.pod index 3c364c1..018698e 100644 --- a/pod/perlop.pod +++ b/pod/perlop.pod @@ -3232,7 +3232,7 @@ strings: $foo = '150' | 105; # yields 255 $foo = 150 | '105'; # yields 255 $foo = '150' | '105'; # yields 255 - $foo = 150 |. 105; # yields string '155' (under ASCII) + $foo = 150 |. 105; # yields string '155' $foo = '150' |. 105; # yields string '155' $foo = 150 |.'105'; # yields string '155' $foo = '150' |.'105'; # yields string '155' @@ -3243,6 +3243,10 @@ strings: The assignment variants of these operators (C<&= |= ^= &.= |.= ^.=>) behave likewise under the feature. +The behavior of these operators is problematic (and subject to change) +if either or both of the strings are encoded in UTF-8 (see +L<perlunicode/Byte and Character Semantics>. + See L<perlfunc/vec> for information on how to manipulate individual bits in a bit vector. diff --git a/pod/perlrebackslash.pod b/pod/perlrebackslash.pod index 55df618..c216f25 100644 --- a/pod/perlrebackslash.pod +++ b/pod/perlrebackslash.pod @@ -589,7 +589,8 @@ the ends of sententces. C<\b{sb}> doesn't do well with text containing embedded newlines, like the source text of the document you are reading. Such text needs to be preprocessed to get rid of the line separators before looking for sentence boundaries. Some people view this as a bug -in the Unicode standard. +in the Unicode standard, and this behavior is quite subject to change in +future Perl versions. =item C<\b{wb}> diff --git a/pod/perlrun.pod b/pod/perlrun.pod index acf2702..7a4e102 100644 --- a/pod/perlrun.pod +++ b/pod/perlrun.pod @@ -419,6 +419,8 @@ B<-D14> is equivalent to B<-Dtls>): 16777216 M trace smart match resolution 33554432 B dump suBroutine definitions, including special Blocks like BEGIN + 67108864 L trace Locale-related info; what gets output is very + subject to change All these flags require B<-DDEBUGGING> when you compile the Perl executable (but see C<:opd> in L<Devel::Peek> or L<re/'debug' mode> diff --git a/pod/perlunicode.pod b/pod/perlunicode.pod index 34dac61..8edbaac 100644 --- a/pod/perlunicode.pod +++ b/pod/perlunicode.pod @@ -4,17 +4,38 @@ perlunicode - Unicode support in Perl =head1 DESCRIPTION +If you haven't already, before reading this document, you should become +familiar with both L<perlunitut> and L<perluniintro>. + +Unicode aims to B<UNI>-fy the en-B<CODE>-ings of all the world's +character sets into a single Standard. For quite a few of the various +coding standards that existed when Unicode was first created, converting +from each to Unicode essentially meant adding a constant to each code +point in the original standard, and converting back meant just +subtracting that same constant. For ASCII and ISO-8859-1, the constant +is 0. For ISO-8859-5, (Cyrillic) the constant is 864; for Hebrew +(ISO-8859-8), it's 1488; Thai (ISO-8859-11), 3424; and so forth. This +made it easy to do the conversions, and facilitated the adoption of +Unicode. + +And it worked; nowadays, those legacy standards are rarely used. Most +everyone uses Unicode. + +Unicode is a comprehensive standard. It specifies many things outside +the scope of Perl, such as how to display sequences of characters. For +a full discussion of all aspects of Unicode, see +L<http://www.unicode.org>. + =head2 Important Caveats +Even though some of this section may not be understandable to you on +first reading, we think it's important enough to highlight some of the +gotchas before delving further, so here goes: + Unicode support is an extensive requirement. While Perl does not implement the Unicode standard or the accompanying technical reports from cover to cover, Perl does support many Unicode features. -People who want to learn to use Unicode in Perl, should probably read -the L<Perl Unicode tutorial, perlunitut|perlunitut> and -L<perluniintro>, before reading -this reference document. - Also, the use of Unicode may present security issues that aren't obvious. Read L<Unicode Security Considerations|http://www.unicode.org/reports/tr36>. @@ -24,8 +45,9 @@ Read L<Unicode Security Considerations|http://www.unicode.org/reports/tr36>. In order to preserve backward compatibility, Perl does not turn on full internal Unicode support unless the pragma -C<use feature 'unicode_strings'> is specified. (This is automatically -selected if you use C<use 5.012> or higher.) Failure to do this can +L<S<C<use feature 'unicode_strings'>>|feature/The 'unicode_strings' feature> +is specified. (This is automatically +selected if you S<C<use 5.012>> or higher.) Failure to do this can trigger unexpected surprises. See L</The "Unicode Bug"> below. This pragma doesn't affect I/O. Nor does it change the internal @@ -35,249 +57,342 @@ filenames. =item Input and Output Layers -Perl knows when a filehandle uses Perl's internal Unicode encodings -(UTF-8, or UTF-EBCDIC if in EBCDIC) if the filehandle is opened with -the C<:encoding(utf8)> layer. Other encodings can be converted to Perl's -encoding on input or from Perl's encoding on output by use of the -C<:encoding(...)> layer. See L<open>. +Use the C<:encoding(...)> layer to read from and write to +filehandles using the specified encoding. (See L<open>.) -To indicate that Perl source itself is in UTF-8, use C<use utf8;>. +=item You should convert your non-ASCII, non-UTF-8 Perl scripts to be +UTF-8. -=item C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts +See L<encoding>. -As a compatibility measure, the C<use utf8> pragma must be explicitly -included to enable recognition of UTF-8 in the Perl scripts themselves -(in string or regular expression literals, or in identifier names) on -ASCII-based machines or to recognize UTF-EBCDIC on EBCDIC-based -machines. B<These are the only times when an explicit C<use utf8> -is needed.> See L<utf8>. +=item C<use utf8> still needed to enable L<UTF-8|/Unicode Encodings> in scripts -=item C<BOM>-marked scripts and UTF-16 scripts autodetected +If your Perl script is itself encoded in L<UTF-8|/Unicode Encodings>, +the S<C<use utf8>> pragma must be explicitly included to enable +recognition of that (in string or regular expression literals, or in +identifier names). B<This is the only time when an explicit S<C<use +utf8>> is needed.> (See L<utf8>). -If a Perl script begins marked with the Unicode C<BOM> (UTF-16LE, UTF16-BE, -or UTF-8), or if the script looks like non-C<BOM>-marked UTF-16 of either -endianness, Perl will correctly read in the script as Unicode. -(C<BOM>less UTF-8 cannot be effectively recognized or differentiated from -ISO 8859-1 or other eight-bit encodings.) +=item C<BOM>-marked scripts and L<UTF-16|/Unicode Encodings> scripts autodetected -=item C<use encoding> needed to upgrade non-Latin-1 byte strings - -By default, there is a fundamental asymmetry in Perl's Unicode model: -implicit upgrading from byte strings to Unicode strings assumes that -they were encoded in I<ISO 8859-1 (Latin-1)>, but Unicode strings are -downgraded with UTF-8 encoding. This happens because the first 256 -codepoints in Unicode happens to agree with Latin-1. - -See L</"Byte and Character Semantics"> for more details. +However, if a Perl script begins with the Unicode C<BOM> (UTF-16LE, +UTF16-BE, or UTF-8), or if the script looks like non-C<BOM>-marked +UTF-16 of either endianness, Perl will correctly read in the script as +the appropriate Unicode encoding. (C<BOM>-less UTF-8 cannot be +effectively recognized or differentiated from ISO 8859-1 or other +eight-bit encodings.) =back =head2 Byte and Character Semantics -Perl uses logically-wide characters to represent strings internally. - -Starting in Perl 5.14, Perl-level operations work with -characters rather than bytes within the scope of a -C<L<use feature 'unicode_strings'|feature>> (or equivalently -C<use 5.012> or higher). (This is not true if bytes have been -explicitly requested by C<L<use bytes|bytes>>, nor necessarily true -for interactions with the platform's operating system.) - -For earlier Perls, and when C<unicode_strings> is not in effect, Perl -provides a fairly safe environment that can handle both types of -semantics in programs. For operations where Perl can unambiguously -decide that the input data are characters, Perl switches to character -semantics. For operations where this determination cannot be made -without additional information from the user, Perl decides in favor of -compatibility and chooses to use byte semantics. - -When C<use locale> (but not C<use locale ':not_characters'>) is in -effect, Perl uses the rules associated with the current locale. -(C<use locale> overrides C<use feature 'unicode_strings'> in the same scope; -while C<use locale ':not_characters'> effectively also selects -C<use feature 'unicode_strings'> in its scope; see L<perllocale>.) -Otherwise, Perl uses the platform's native -byte semantics for characters whose code points are less than 256, and -Unicode rules for those greater than 255. That means that non-ASCII -characters are undefined except for their -ordinal numbers. This means that none have case (upper and lower), nor are any -a member of character classes, like C<[:alpha:]> or C<\w>. (But all do belong -to the C<\W> class or the Perl regular expression extension C<[:^alpha:]>.) - -This behavior preserves compatibility with earlier versions of Perl, -which allowed byte semantics in Perl operations only if -none of the program's inputs were marked as being a source of Unicode -character data. Such data may come from filehandles, from calls to -external programs, from information provided by the system (such as C<%ENV>), -or from literals and constants in the source text. - -The C<utf8> pragma is primarily a compatibility device that enables -recognition of UTF-(8|EBCDIC) in literals encountered by the parser. -Note that this pragma is only required while Perl defaults to byte -semantics; when character semantics become the default, this pragma -may become a no-op. See L<utf8>. - -If strings operating under byte semantics and strings with Unicode -character data are concatenated, the new string will have -character semantics. This can cause surprises: See L</BUGS>, below. -You can choose to be warned when this happens. See C<L<encoding::warnings>>. - -Under character semantics, many operations that formerly operated on -bytes now operate on characters. A character in Perl is -logically just a number ranging from 0 to 2**31 or so. Larger -characters may encode into longer sequences of bytes internally, but -this internal detail is mostly hidden for Perl code. -See L<perluniintro> for more. - -=head2 Effects of Character Semantics - -Character semantics have the following effects: +Before Unicode, most encodings used 8 bits (a single byte) to encode +each character. Thus a character was a byte, and a byte was a +character, and there could be only 256 or fewer possible characters. +"Byte Semantics" in the title of this section refers to +this behavior. There was no need to distinguish between "Byte" and +"Character". + +Then along comes Unicode which has room for over a million characters +(and Perl allows for even more). This means that a character may +require more than a single byte to represent it, and so the two terms +are no longer equivalent. What matter are the characters as whole +entities, and not usually the bytes that comprise them. That's what the +term "Character Semantics" in the title of this section refers to. + +Perl had to change internally to decouple "bytes" from "characters". +It is important that you too change your ideas, if you haven't already, +so that "byte" and "character" no longer mean the same thing in your +mind. + +The basic building block of Perl strings has always been a "character". +The changes basically come down to that the implementation no longer +thinks that a character is always just a single byte. + +There are various things to note: + +=over 4 + +=item * + +String handling functions, for the most part, continue to operate in +terms of characters. C<length()>, for example, returns the number of +characters in a string, just as before. But that number no longer is +necessarily the same as the number of bytes in the string (there may be +more bytes than characters). The other such functions include +C<chop()>, C<chomp()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>, +C<sort()>, C<sprintf()>, and C<write()>. + +The exceptions are: =over 4 =item * +the bit-oriented C<vec> + +E<nbsp> + +=item * + +the byte-oriented C<pack>/C<unpack> C<"C"> format + +However, the C<W> specifier does operate on whole characters, as does the +C<U> specifier. + +=item * + +some operators that interact with the platform's operating system + +Operators dealing with filenames are examples. + +=item * + +when the functions are called from within the scope of the +S<C<L<use bytes|bytes>>> pragma + +Likely, you should use this only for debugging anyway. + +=back + +=item * + Strings--including hash keys--and regular expression patterns may -contain characters that have an ordinal value larger than 255. +contain characters that have ordinal values larger than 255. If you use a Unicode editor to edit your program, Unicode characters may occur directly within the literal strings in UTF-8 encoding, or UTF-16. (The former requires a C<BOM> or C<use utf8>, the latter requires a C<BOM>.) -Unicode characters can also be added to a string by using the C<\N{U+...}> -notation. The Unicode code for the desired character, in hexadecimal, -should be placed in the braces, after the C<U>. For instance, a smiley face is -C<\N{U+263A}>. - -Alternatively, you can use the C<\x{...}> notation for characters C<0x100> and -above. For characters below C<0x100> you may get byte semantics instead of -character semantics; see L</The "Unicode Bug">. On EBCDIC machines there is -the additional problem that the value for such characters gives the EBCDIC -character rather than the Unicode one, thus it is more portable to use -C<\N{U+...}> instead. +L<perluniintro/Creating Unicode> gives other ways to place non-ASCII +characters in your strings. -Additionally, you can use the C<\N{...}> notation and put the official -Unicode character name within the braces, such as -C<\N{WHITE SMILING FACE}>. This automatically loads the L<charnames> -module with the C<:full> and C<:short> options. If you prefer different -options for this module, you can instead, before the C<\N{...}>, -explicitly load it with your desired options; for example, +=item * - use charnames ':loose'; +The C<chr()> and C<ord()> functions work on whole characters. =item * -If an appropriate L<encoding> is specified, identifiers within the -Perl script may contain Unicode alphanumeric characters, including -ideographs. Perl does not currently attempt to canonicalize variable -names. +Regular expressions match whole characters. For example, C<"."> matches +a whole character instead of only a single byte. =item * -Regular expressions match characters instead of bytes. C<"."> matches -a character instead of a byte. +The C<tr///> operator translates whole characters. (Note that the +C<tr///CU> functionality has been removed. For similar functionality to +that, see C<pack('U0', ...)> and C<pack('C0', ...)>). =item * -Bracketed character classes in regular expressions match characters instead of -bytes and match against the character properties specified in the -Unicode properties database. C<\w> can be used to match a Japanese -ideograph, for instance. +C<scalar reverse()> reverses by character rather than by byte. =item * -Named Unicode properties, scripts, and block ranges may be used (like bracketed -character classes) by using the C<\p{}> "matches property" construct and -the C<\P{}> negation, "doesn't match property". -See L</"Unicode Character Properties"> for more details. +The bit string operators, C<& | ^ ~> and (starting in v5.22) +C<&. |. ^. ~.> can operate on characters that don't fit into a byte. +However, the current behavior is likely to change. You should not use +these operators on strings that are encoded in UTF-8. If you're not +sure about the encoding of a string, downgrade it before using any of +these operators; you can use +L<C<utf8::utf8_downgrade()>|utf8/Utility functions>. -You can define your own character properties and use them -in the regular expression with the C<\p{}> or C<\P{}> construct. -See L</"User-Defined Character Properties"> for more details. +=back -=item * +The bottom line is that Perl has always practiced "Character Semantics", +but with the advent of Unicode, that is now different than "Byte +Semantics". -The special pattern C<\X> matches a logical character, an "extended grapheme -cluster" in Standardese. In Unicode what appears to the user to be a single -character, for example an accented C<G>, may in fact be composed of a sequence -of characters, in this case a C<G> followed by an accent character. C<\X> -will match the entire sequence. +=head2 ASCII Rules versus Unicode Rules + +Before Unicode, when a character was a byte was a character, +Perl knew only about the 128 characters defined by ASCII, code points 0 +through 127 (except for under S<C<use locale>>). That left the code +points 128 to 255 as unassigned, and available for whatever use a +program might want. The only semantics they have is their ordinal +numbers, and that they are members of none of the non-negative character +classes. None are considered to match C<\w> for example, but all match +C<\W>. + +Unicode, of course, assigns each of those code points a particular +meaning (along with ones above 255). To preserve backward +compatibility, Perl only uses the Unicode meanings when there is some +indication that Unicode is what is intended; otherwise the non-ASCII +code points remain treated as if they are unassigned. + +Here are the ways that Perl knows that a string should be treated as +Unicode: + +=over =item * -The C<tr///> operator translates characters instead of bytes. Note -that the C<tr///CU> functionality has been removed. For similar -functionality see pack('U0', ...) and pack('C0', ...). +Within the scope of S<C<use utf8>> + +If the whole program is Unicode (signified by using 8-bit B<U>nicode +B<T>ransformation B<F>ormat), then all strings within it must be +Unicode. =item * -Case translation operators use the Unicode case translation tables -when character input is provided. Note that C<uc()>, or C<\U> in -interpolated strings, translates to uppercase, while C<ucfirst>, -or C<\u> in interpolated strings, translates to titlecase in languages -that make the distinction (which is equivalent to uppercase in languages -without the distinction). +Within the scope of +L<S<C<use feature 'unicode_strings'>>|feature/The 'unicode_strings' feature> + +This pragma was created so you can explicitly tell Perl that operations +executed within its scope are to use Unicode rules. More operations are +affected with newer perls. See L</The "Unicode Bug">. =item * -Most operators that deal with positions or lengths in a string will -automatically switch to using character positions, including -C<chop()>, C<chomp()>, C<substr()>, C<pos()>, C<index()>, C<rindex()>, -C<sprintf()>, C<write()>, and C<length()>. An operator that -specifically does not switch is C<vec()>. Operators that really don't -care include operators that treat strings as a bucket of bits such as -C<sort()>, and operators dealing with filenames. +Within the scope of S<C<use 5.012>> or higher + +This implicitly turns on S<C<use feature 'unicode_strings'>>. =item * -The C<pack()>/C<unpack()> letter C<C> does I<not> change, since it is often -used for byte-oriented formats. Again, think C<char> in the C language. +Within the scope of +L<S<C<use locale 'not_characters'>>|perllocale/Unicode and UTF-8>, +or L<S<C<use locale>>|perllocale> and the current +locale is a UTF-8 locale. -There is a new C<U> specifier that converts between Unicode characters -and code points. There is also a C<W> specifier that is the equivalent of -C<chr>/C<ord> and properly handles character values even if they are above 255. +The former is defined to imply Unicode handling; and the latter +indicates a Unicode locale, hence a Unicode interpretation of all +strings within it. =item * -The C<chr()> and C<ord()> functions work on characters, similar to -C<pack("W")> and C<unpack("W")>, I<not> C<pack("C")> and -C<unpack("C")>. C<pack("C")> and C<unpack("C")> are methods for -emulating byte-oriented C<chr()> and C<ord()> on Unicode strings. -While these methods reveal the internal encoding of Unicode strings, -that is not something one normally needs to care about at all. +When the string contains a Unicode-only code point + +Perl has never accepted code points above 255 without them being +Unicode, so their use implies Unicode for the whole string. =item * -The bit string operators, C<& | ^ ~>, can operate on character data. -However, for backward compatibility, such as when using bit string -operations when characters are all less than 256 in ordinal value, one -should not use C<~> (the bit complement) with characters of both -values less than 256 and values greater than 256. Most importantly, -DeMorgan's laws (C<~($x|$y) eq ~$x&~$y> and C<~($x&$y) eq ~$x|~$y>) -will not hold. The reason for this mathematical I<faux pas> is that -the complement cannot return B<both> the 8-bit (byte-wide) bit -complement B<and> the full character-wide bit complement. +When the string contains a Unicode named code point C<\N{...}> + +The C<\N{...}> construct explicitly refers to a Unicode code point, +even if it is one that is also in ASCII. Therefore the string +containing it must be Unicode. =item * -There is a CPAN module, C<L<Unicode::Casing>>, which allows you to define -your own mappings to be used in C<lc()>, C<lcfirst()>, C<uc()>, -C<ucfirst()>, and C<fc> (or their double-quoted string inlined -versions such as C<\U>). -(Prior to Perl 5.16, this functionality was partially provided -in the Perl core, but suffered from a number of insurmountable -drawbacks, so the CPAN module was written instead.) +When the string has come from an external source marked as +Unicode + +The L<C<-C>|perlrun/-C [numberE<sol>list]> command line option can +specify that certain inputs to the program are Unicode, and the values +of this can be read by your Perl code, see L<perlvar/"${^UNICODE}">. + +=item * When the string has been upgraded to UTF-8 + +The function L<C<utf8::utf8_upgrade()>|utf8/Utility functions> +can be explicitly used to permanently (unless a subsequent +C<utf8::utf8_downgrade()> is called) cause a string to be treated as +Unicode. + +=item * There are additional methods for regular expression patterns + +A pattern that is compiled with the L<C<E<sol>u>|perlre/E<sol>u> modifier is +treated as Unicode. Under the C</d> modifier, there are several other +indications of Unicode; see L<perlre/E<sol>d>. =back +Note that all of the above are overridden within the scope of +C<L<use bytes|bytes>>; but you should be using this pragma only for +debugging. + +Note also that some interactions with the platform's operating system +never use Unicode rules. + +When Unicode rules are in effect: + =over 4 =item * -And finally, C<scalar reverse()> reverses by character rather than by byte. +Case translation operators use the Unicode case translation tables. + +Note that C<uc()>, or C<\U> in interpolated strings, translates to +uppercase, while C<ucfirst>, or C<\u> in interpolated strings, +translates to titlecase in languages that make the distinction (which is +equivalent to uppercase in languages without the distinction). + +There is a CPAN module, C<L<Unicode::Casing>>, which allows you to +define your own mappings to be used in C<lc()>, C<lcfirst()>, C<uc()>, +C<ucfirst()>, and C<fc> (or their double-quoted string inlined versions +such as C<\U>). (Prior to Perl 5.16, this functionality was partially +provided in the Perl core, but suffered from a number of insurmountable +drawbacks, so the CPAN module was written instead.) + +=item * + +Character classes in regular expressions match based on the character +properties specified in the Unicode properties database. + +C<\w> can be used to match a Japanese ideograph, for instance; and +C<[[:digit:]]> a Bengali number. + +=item * + +Named Unicode properties, scripts, and block ranges may be used (like +bracketed character classes) by using the C<\p{}> "matches property" +construct and the C<\P{}> negation, "doesn't match property". + +See L</"Unicode Character Properties"> for more details. + +You can define your own character properties and use them +in the regular expression with the C<\p{}> or C<\P{}> construct. +See L</"User-Defined Character Properties"> for more details. =back +=head2 Extended Grapheme Clusters (Logical characters) + +Consider a character, say C<H>. It could appear with various marks around it, +such as an acute accent, or a circumflex, or various hooks, circles, arrows, +I<etc.>, above, below, to one side or the other, I<etc>. There are many +possibilities among the world's languages. The number of combinations is +astronomical, and if there were a character for each combination, it would +soon exhaust Unicode's more than a million possible characters. So Unicode +took a different approach: there is a character for the base C<H>, and a +character for each of the possible marks, and these can be variously combined +to get a final logical character. So a logical character--what appears to be a +single character--can be a sequence of more than one individual characters. +The Unicode standard calls these "extended grapheme clusters" (which +is an improved version of the no-longer much used "grapheme cluster"); +Perl furnishes the C<\X> regular expression construct to match such +sequences in their entirety. + +But Unicode's intent is to unify the existing character set standards and +practices, and several pre-existing standards have single characters that +mean the same thing as some of these combinations, like ISO-8859-1, +which has quite a few of them. For example, C<"LATIN CAPITAL LETTER E +WITH ACUTE"> was already in this standard when Unicode came along. +Unicode therefore added it to its repertoire as that single character. +But this character is considered by Unicode to be equivalent to the +sequence consisting of the character C<"LATIN CAPITAL LETTER E"> +followed by the character C<"COMBINING ACUTE ACCENT">. + +C<"LATIN CAPITAL LETTER E WITH ACUTE"> is called a "pre-composed" +character, and its equivalence with the "E" and the "COMBINING ACCENT" +sequence is called canonical equivalence. All pre-composed characters +are said to have a decomposition (into the equivalent sequence), and the +decomposition type is also called canonical. A string may be comprised +as much as possible of precomposed characters, or it may be comprised of +entirely decomposed characters. Unicode calls these respectively, +"Normalization Form Composed" (NFC) and "Normalization Form Decomposed". +The C<L<Unicode::Normalize>> module contains functions that convert +between the two. A string may also have both composed characters and +decomposed characters; this module can be used to make it all one or the +other. + +You may be presented with strings in any of these equivalent forms. +There is currently nothing in Perl 5 that ignores the differences. So +you'll have to specially hanlde it. The usual advice is to convert your +inputs to C<NFD> before processing further. + +For more detailed information, see L<http://unicode.org/reports/tr15/>. + =head2 Unicode Character Properties (The only time that Perl considers a sequence of individual code @@ -307,7 +422,7 @@ can take on several different values, such as C<Left>, C<Right>, C<Whitespace>, and others. To match these, one needs to specify both the property name (C<Bidi_Class>), AND the value being matched against -(C<Left>, C<Right>, etc.). This is done, as in the examples above, by having the +(C<Left>, C<Right>, I<etc.>). This is done, as in the examples above, by having the two components separated by an equal sign (or interchangeably, a colon), like C<\p{Bidi_Class: Left}>. @@ -368,8 +483,8 @@ all of which match C<Cased> under C</i> matching. This set also includes its subsets C<PosixUpper> and C<PosixLower> both of which under C</i> match C<PosixAlpha>. (The difference between these sets is that some things, such as Roman -numerals, come in both upper and lower case so they are C<Cased>, but aren't considered -letters, so they aren't C<Cased_Letter>s.) +numerals, come in both upper and lower case so they are C<Cased>, but +aren't considered letters, so they aren't C<Cased_Letter>'s.) See L</Beyond Unicode code points> for special considerations when matching Unicode properties against non-Unicode code points. @@ -381,7 +496,7 @@ usual categorization of a character" (from L<http://www.unicode.org/reports/tr44>). The compound way of writing these is like C<\p{General_Category=Number}> -(short, C<\p{gc:n}>). But Perl furnishes shortcuts in which everything up +(short: C<\p{gc:n}>). But Perl furnishes shortcuts in which everything up through the equal or colon separator is omitted. So you can instead just write C<\pN>. @@ -486,7 +601,7 @@ The world's languages are written in many different scripts. This sentence written in Cyrillic, and Greek is written in, well, Greek; Japanese mainly in Hiragana or Katakana. There are many more. -The Unicode Script and Script_Extensions properties give what script a +The Unicode C<Script> and C<Script_Extensions> properties give what script a given character is in. Either property can be specified with the compound form like C<\p{Script=Hebrew}> (short: C<\p{sc=hebr}>), or @@ -528,10 +643,12 @@ C<Script_Extensions> is thus an improved C<Script>, in which there are fewer characters in the C<Common> script, and correspondingly more in other scripts. It is new in Unicode version 6.0, and its data are likely to change significantly in later releases, as things get sorted out. +New code should probably be using C<Script_Extensions> and not plain +C<Script>. (Actually, besides C<Common>, the C<Inherited> script, contains characters that are used in multiple scripts. These are modifier -characters which modify other characters, and inherit the script value +characters which inherit the script value of the controlling character. Some of these are used in many scripts, and so go into C<Inherited> in both C<Script> and C<Script_Extensions>. Others are used in just a few scripts, so are in C<Inherited> in @@ -548,7 +665,8 @@ A complete list of scripts and their shortcuts is in L<perluniprops>. =head3 B<Use of the C<"Is"> Prefix> -For backward compatibility (with Perl 5.6), all properties mentioned +For backward compatibility (with Perl 5.6), all properties writable +without using the compound form mentioned so far may have C<Is> or C<Is_> prepended to their name, so C<\P{Is_Lu}>, for example, is equal to C<\P{Lu}>, and C<\p{IsScript:Arabic}> is equal to C<\p{Arabic}>. @@ -560,10 +678,10 @@ characters. The difference between scripts and blocks is that the concept of scripts is closer to natural languages, while the concept of blocks is more of an artificial grouping based on groups of Unicode characters with consecutive ordinal values. For example, the C<"Basic Latin"> -block is all characters whose ordinals are between 0 and 127, inclusive; in +block is all the characters whose ordinals are between 0 and 127, inclusive; in other words, the ASCII characters. The C<"Latin"> script contains some letters from this as well as several other blocks, like C<"Latin-1 Supplement">, -C<"Latin Extended-A">, etc., but it does not contain all the characters from +C<"Latin Extended-A">, I<etc.>, but it does not contain all the characters from those blocks. It does not, for example, contain the digits 0-9, because those digits are shared across many scripts, and hence are in the C<Common> script. @@ -578,34 +696,28 @@ with the nuts and bolts of Unicode. Block names are matched in the compound form, like C<\p{Block: Arrows}> or C<\p{Blk=Hebrew}>. Unlike most other properties, only a few block names have a -Unicode-defined short name. But Perl does provide a (slight) shortcut: You -can say, for example C<\p{In_Arrows}> or C<\p{In_Hebrew}>. For backwards -compatibility, the C<In> prefix may be omitted if there is no naming conflict -with a script or any other property, and you can even use an C<Is> prefix -instead in those cases. But it is not a good idea to do this, for a couple -reasons: - -=over 4 - -=item 1 - -It is confusing. There are many naming conflicts, and you may forget some. -For example, C<\p{Hebrew}> means the I<script> Hebrew, and NOT the I<block> -Hebrew. But would you remember that 6 months from now? - -=item 2 - -It is unstable. A new version of Unicode may preempt the current meaning by -creating a property with the same name. There was a time in very early Unicode -releases when C<\p{Hebrew}> would have matched the I<block> Hebrew; now it -doesn't. - -=back - -Some people prefer to always use C<\p{Block: foo}> and C<\p{Script: bar}> -instead of the shortcuts, whether for clarity, because they can't remember the -difference between 'In' and 'Is' anyway, or they aren't confident that those who -eventually will read their code will know that difference. +Unicode-defined short name. But Perl does provide a (slight, no longer +recommended) shortcut: You can say, for example C<\p{In_Arrows}> or +C<\p{In_Hebrew}>. + +For backwards compatibility, the C<In> prefix may be +omitted if there is no naming conflict with a script or any other +property, and you can even use an C<Is> prefix instead in those cases. +But don't do this for new code because your code could break in new +releases, and this has already happened: There was a time in very +early Unicode releases when C<\p{Hebrew}> would have matched the +I<block> Hebrew; now it doesn't. + +Using the C<In> prefix avoids this ambiguity, so far. But new versions +of Unicode continue to add new properties whose names begin with C<In>. +There is a possibility that one of them someday will conflict with your +usage. Since this is just a Perl extension, Unicode's name will take +precedence and your code will become broken. Also, Unicode is free to +add a script whose name begins with C<In>; that would cause problems. + +So it's clearer and best to use the compound form when specifying +blocks. And be sure that is what you really really want to do. In most +cases scripts are what you want instead. A complete list of blocks and their shortcuts is in L<perluniprops>. @@ -662,45 +774,19 @@ spacing horizontally. Matches a character that has a non-canonical decomposition. -To understand the use of this rarely used I<property=value> combination, it is -necessary to know some basics about decomposition. -Consider a character, say H. It could appear with various marks around it, -such as an acute accent, or a circumflex, or various hooks, circles, arrows, -I<etc.>, above, below, to one side or the other, etc. There are many -possibilities among the world's languages. The number of combinations is -astronomical, and if there were a character for each combination, it would -soon exhaust Unicode's more than a million possible characters. So Unicode -took a different approach: there is a character for the base H, and a -character for each of the possible marks, and these can be variously combined -to get a final logical character. So a logical character--what appears to be a -single character--can be a sequence of more than one individual characters. -This is called an "extended grapheme cluster"; Perl furnishes the C<\X> -regular expression construct to match such sequences. - -But Unicode's intent is to unify the existing character set standards and -practices, and several pre-existing standards have single characters that -mean the same thing as some of these combinations. An example is ISO-8859-1, -which has quite a few of these in the Latin-1 range, an example being C<"LATIN -CAPITAL LETTER E WITH ACUTE">. Because this character was in this pre-existing -standard, Unicode added it to its repertoire. But this character is considered -by Unicode to be equivalent to the sequence consisting of the character -C<"LATIN CAPITAL LETTER E"> followed by the character C<"COMBINING ACUTE ACCENT">. - -C<"LATIN CAPITAL LETTER E WITH ACUTE"> is called a "pre-composed" character, and -its equivalence with the sequence is called canonical equivalence. All -pre-composed characters are said to have a decomposition (into the equivalent -sequence), and the decomposition type is also called canonical. - -However, many more characters have a different type of decomposition, a -"compatible" or "non-canonical" decomposition. The sequences that form these -decompositions are not considered canonically equivalent to the pre-composed -character. An example, again in the Latin-1 range, is the C<"SUPERSCRIPT ONE">. -It is somewhat like a regular digit 1, but not exactly; its decomposition -into the digit 1 is called a "compatible" decomposition, specifically a +The L</Extended Grapheme Clusters (Logical characters)> section above +talked about canonical decompositions. However, many more characters +have a different type of decomposition, a "compatible" or +"non-canonical" decomposition. The sequences that form these +decompositions are not considered canonically equivalent to the +pre-composed character. An example is the C<"SUPERSCRIPT ONE">. It is +somewhat like a regular digit 1, but not exactly; its decomposition into +the digit 1 is called a "compatible" decomposition, specifically a "super" decomposition. There are several such compatibility -decompositions (see L<http://www.unicode.org/reports/tr44>), including one -called "compat", which means some miscellaneous type of decomposition -that doesn't fit into the decomposition categories that Unicode has chosen. +decompositions (see L<http://www.unicode.org/reports/tr44>), including +one called "compat", which means some miscellaneous type of +decomposition that doesn't fit into the other decomposition categories +that Unicode has chosen. Note that most Unicode characters don't have a decomposition, so their decomposition type is C<"None">. @@ -737,8 +823,8 @@ Mnemonic: Perl's (original) word. =item B<C<\p{Posix...}>> -There are several of these, which are equivalents using the C<\p{}> -notation for Posix classes and are described in +There are several of these, which are equivalents, using the C<\p{}> +notation, for Posix classes and are described in L<perlrecharclass/POSIX Character Classes>. =item B<C<\p{Present_In: *}>> (Short: C<\p{In=*}>) @@ -918,7 +1004,7 @@ You could also have used the existing block property names: Suppose you wanted to match only the allocated characters, not the raw block ranges: in other words, you want to remove -the non-characters: +the unassigned characters: sub InKana { return <<'END'; @@ -999,31 +1085,27 @@ Level 1 - Basic Unicode Support =over 4 -=item [1] - -C<\x{...}> - -=item [2] - -C<\p{...}> C<\P{...}> +=item [1] C<\N{U+...}> and C<\x{...}> -=item [3] +=item [2] C<\p{...}> C<\P{...}> -supports not only minimal list, but all Unicode character properties (see Unicode Character Properties above) +=item [3] supports not only minimal list, but all Unicode character +properties (see Unicode Character Properties above) -=item [4] +=item [4] C<\d> C<\D> C<\s> C<\S> C<\w> C<\W> C<\X> C<[:I<prop>:]> +C<[:^I<prop>:]> -C<\d> C<\D> C<\s> C<\S> C<\w> C<\W> C<\X> C<[:I<prop>:]> C<[:^I<prop>:]> +=item [5] The experimental feature starting in v5.18 C<"(?[...])"> accomplishes +this. -=item [5] - -The experimental feature in v5.18 C<"(?[...])"> accomplishes this. See -L<perlre/(?[ ])>. If you don't want to use an experimental feature, -you can use one of the following: +See L<perlre/(?[ ])>. If you don't want to use an experimental +feature, you can use one of the following: =over 4 -=item * Regular expression look-ahead +=item * + +Regular expression look-ahead You can mimic class subtraction using lookahead. For example, what UTS#18 might write as @@ -1041,47 +1123,60 @@ But in this particular example, you probably really want which will match assigned characters known to be part of the Greek script. -=item * CPAN module C<L<Unicode::Regex::Set>> +=item * + +CPAN module C<L<Unicode::Regex::Set>> It does implement the full UTS#18 grouping, intersection, union, and removal (subtraction) syntax. -=item * L</"User-Defined Character Properties"> +=item * + +L</"User-Defined Character Properties"> C<"+"> for union, C<"-"> for removal (set-difference), C<"&"> for intersection =back -=item [6] - -C<\b> C<\B> +=item [6] C<\b> C<\B> =item [7] +Note that Perl does Full case-folding in matching, not Simple: -Note that Perl does Full case-folding in matching (but with bugs), not -Simple: for example C<U+1F88> is equivalent to C<U+1F00 U+03B9>, instead of -just C<U+1F80>. This difference matters mainly for certain Greek capital +For example C<U+1F88> is equivalent to C<U+1F00 U+03B9>, instead of just +C<U+1F80>. This difference matters mainly for certain Greek capital letters with certain modifiers: the Full case-folding decomposes the letter, while the Simple case-folding would map it to a single character. =item [8] +Perl treats C<\n> as the start- and end-line delimiter. Unicode +specifies more characters that should be so-interpreted. -Should do C<^> and C<$> also on C<U+000B> (C<\v> in C), C<FF> (C<\f>), -C<CR> (C<\r>), C<CRLF> (C<\r\n>), C<NEL> (C<U+0085>), C<LS> (C<U+2028>), -and C<PS> (C<U+2029>); should also affect C<E<lt>E<gt>>, C<$.>, and -script line numbers; should not split lines within C<CRLF> (i.e. there -is no empty line between C<\r> and C<\n>). For C<CRLF>, try the -C<:crlf> layer (see L<PerlIO>). +These are: -=item [9] + VT U+000B (\v in C) + FF U+000C (\f) + CR U+000D (\r) + NEL U+0085 + LS U+2028 + PS U+2029 -Linebreaking conformant with L<UAX#14 "Unicode Line Breaking -Algorithm"|http://www.unicode.org/reports/tr14> -is available through the C<L<Unicode::LineBreak>> module. +C<^> and C<$> in regular expression patterns are supposed to match all +these, but don't. +These characters also don't, but should, affect C<< <> >> C<$.>, and +script line numbers. -=item [10] +Also, lines should not be split within C<CRLF> (i.e. there is no +empty line between C<\r> and C<\n>). For C<CRLF>, try the C<:crlf> +layer (see L<PerlIO>). +=item [9] But C<L<Unicode::LineBreak>> is available. + +This module supplies line breaking conformant with +L<UAX#14 "Unicode Line Breaking Algorithm"|http://www.unicode.org/reports/tr14>. + +=item [10] UTF-8/UTF-EBDDIC used in Perl allows not only C<U+10000> to C<U+10FFFF> but also beyond C<U+10FFFF> @@ -1144,8 +1239,11 @@ numbers. To use these numbers, various encodings are needed. UTF-8 UTF-8 is a variable-length (1 to 4 bytes), byte-order independent -encoding. For ASCII (and we really do mean 7-bit ASCII, not another -8-bit encoding), UTF-8 is transparent. +encoding. In most of Perl's documentation, including elsewhere in this +document, the term "UTF-8" means also "UTF-EBCDIC". But in this section, +"UTF-8" refers only to the encoding used on ASCII platforms. It is a +superset of 7-bit US-ASCII, so anything encoded in ASCII has the +identical representation when encoded in UTF-8. The following table is from Unicode 3.2. @@ -1192,11 +1290,19 @@ they are forbidden. UTF-EBCDIC -Like UTF-8 but EBCDIC-safe, in the way that UTF-8 is ASCII-safe. +Like UTF-8, but EBCDIC-safe, in the way that UTF-8 is ASCII-safe. +This means that all the basic characters (which includes all +those that have ASCII equivalents (like C<"A">, C<"0">, C<"%">, I<etc.>) +are the same in both EBCDIC and UTF-EBCDIC.) + +UTF-EBCDIC is used on EBCDIC platforms. The largest Unicode code points +take 5 bytes to represent (instead of 4 in UTF-8), and Perl extends it +to a maximum of 7 bytes to encode pode points up to what can fit in a +32-bit word (instead of 13 bytes and a 64-bit word in UTF-8). =item * -UTF-16, UTF-16BE, UTF-16LE, Surrogates, and C<BOM>s (Byte Order Marks) +UTF-16, UTF-16BE, UTF-16LE, Surrogates, and C<BOM>'s (Byte Order Marks) The followings items are mostly for reference and general Unicode knowledge, Perl doesn't use these constructs internally. @@ -1228,7 +1334,7 @@ transfer is required either UTF-16BE (big-endian) or UTF-16LE This introduces another problem: what if you just know that your data is UTF-16, but you don't know which endianness? Byte Order Marks, or -C<BOM>s, are a solution to this. A special character has been reserved +C<BOM>'s, are a solution to this. A special character has been reserved in Unicode to function as a byte order marker: the character with the code point C<U+FEFF> is the C<BOM>. @@ -1236,7 +1342,8 @@ The trick is that if you read a C<BOM>, you will know the byte order, since if it was written on a big-endian platform, you will read the bytes C<0xFE 0xFF>, but if it was written on a little-endian platform, you will read the bytes C<0xFF 0xFE>. (And if the originating platform -was writing in UTF-8, you will read the bytes C<0xEF 0xBB 0xBF>.) +was writing in ASCII platform UTF-8, you will read the bytes +C<0xEF 0xBB 0xBF>.) The way this trick works is that the character with the code point C<U+FFFE> is not supposed to be in input streams, so the @@ -1261,7 +1368,7 @@ before 5.14.) UTF-32, UTF-32BE, UTF-32LE -The UTF-32 family is pretty much like the UTF-16 family, expect that +The UTF-32 family is pretty much like the UTF-16 family, except that the units are 32-bit, and therefore the surrogate scheme is not needed. UTF-32 is a fixed-width encoding. The C<BOM> signatures are C<0x00 0x00 0xFE 0xFF> for BE and C<0xFF 0xFE 0x00 0x00> for LE. @@ -1371,8 +1478,8 @@ sensible rules, while generally warning, using the C<"non_unicode"> category. For example, C<uc("\x{11_0000}")> will generate such a warning, returning the input parameter as its result, since Perl defines the uppercase of every non-Unicode code point to be the code point -itself. In fact, all the case changing operations, not just -uppercasing, work this way. +itself. (All the case changing operations, not just uppercasing, work +this way.) The situation with matching Unicode properties in regular expressions, the C<\p{}> and C<\P{}> constructs, against these code points is not as @@ -1472,7 +1579,9 @@ through C<0x10FFFF>.) =head2 Security Implications of Unicode -Read L<Unicode Security Considerations|http://www.unicode.org/reports/tr36>. +First, read +L<Unicode Security Considerations|http://www.unicode.org/reports/tr36>. + Also, note the following: =over 4 @@ -1501,25 +1610,25 @@ modifiers. Details are given in L<perlre/Character set modifiers>. =back As discussed elsewhere, Perl has one foot (two hooves?) planted in -each of two worlds: the old world of bytes and the new world of -characters, upgrading from bytes to characters when necessary. +each of two worlds: the old world of ASCII and single-byte locales, and +the new world of Unicode, upgrading when necessary. If your legacy code does not explicitly use Unicode, no automatic -switch-over to characters should happen. Characters shouldn't get -downgraded to bytes, either. It is possible to accidentally mix bytes -and characters, however (see L<perluniintro>), in which case C<\w> in -regular expressions might start behaving differently (unless the C</a> -modifier is in effect). Review your code. Use warnings and the C<strict> pragma. +switch-over to Unicode should happen. =head2 Unicode in Perl on EBCDIC -The way Unicode is handled on EBCDIC platforms is still -experimental. On such platforms, references to UTF-8 encoding in this -document and elsewhere should be read as meaning the UTF-EBCDIC -specified in Unicode Technical Report 16, unless ASCII vs. EBCDIC issues -are specifically discussed. There is no C<utfebcdic> pragma or -C<":utfebcdic"> layer; rather, C<"utf8"> and C<":utf8"> are reused to mean -the platform's "natural" 8-bit encoding of Unicode. See L<perlebcdic> -for more discussion of the issues. +Unicode is supported on EBCDIC platforms. See L<perlebcdic>. + +Unless ASCII vs. EBCDIC issues are specifically being discussed, +references to UTF-8 encoding in this document and elsewhere should be +read as meaning UTF-EBCDIC on EBCDIC platforms. +See L<perlebcdic/Unicode and UTF>. + +Because UTF-EBCDIC is so similar to UTF-8, the differences are mostly +hidden from you; S<C<use utf8>> (and NOT something like +S<C<use utfebcdic>>) declares the the script is in the platform's +"native" 8-bit encoding of Unicode. (Similarly for the C<":utf8"> +layer.) =head2 Locales @@ -1527,16 +1636,16 @@ See L<perllocale/Unicode and UTF-8> =head2 When Unicode Does Not Happen -While Perl does have extensive ways to input and output in Unicode, -and a few other "entry points" like the C<@ARGV> array (which can sometimes be -interpreted as UTF-8), there are still many places where Unicode -(in some encoding or another) could be given as arguments or received as -results, or both, but it is not. +There are still many places where Unicode (in some encoding or +another) could be given as arguments or received as results, or both in +Perl, but it is not, in spite of Perl having extensive ways to input and +output in Unicode, and a few other "entry points" like the C<@ARGV> +array (which can sometimes be interpreted as UTF-8). The following are such interfaces. Also, see L</The "Unicode Bug">. For all of these interfaces Perl currently (as of v5.16.0) simply assumes byte strings both as arguments -and results, or UTF-8 strings if the (problematic) C<encoding> pragma has been used. +and results, or UTF-8 strings if the (deprecated) C<encoding> pragma has been used. One reason that Perl does not attempt to resolve the role of Unicode in these situations is that the answers are highly dependent on the operating @@ -1576,32 +1685,50 @@ C<readdir>, C<readlink> =head2 The "Unicode Bug" -The term, "Unicode bug" has been applied to an inconsistency -on ASCII platforms with the -Unicode code points in the C<Latin-1 Supplement> block, that -is, between 128 and 255. Without a locale specified, unlike all other -characters or code points, these characters have very different semantics in -byte semantics versus character semantics, unless -C<use feature 'unicode_strings'> is specified, directly or indirectly. -(It is indirectly specified by a C<use v5.12> or higher.) - -In character semantics these upper-Latin1 characters are interpreted as -Unicode code points, which means -they have the same semantics as Latin-1 (ISO-8859-1). - -In byte semantics (without C<unicode_strings>), they are considered to -be unassigned characters, meaning that the only semantics they have is -their ordinal numbers, and that they are -not members of various character classes. None are considered to match C<\w> -for example, but all match C<\W>. - -Perl 5.12.0 added C<unicode_strings> to force character semantics on -these code points in some circumstances, which fixed portions of the -bug; Perl 5.14.0 fixed almost all of it; and Perl 5.16.0 fixed the -remainder (so far as we know, anyway). The lesson here is to enable -C<unicode_strings> to avoid the headaches described below. - -The old, problematic behavior affects these areas: +The term, "Unicode bug" has been applied to an inconsistency with the +code points in the C<Latin-1 Supplement> block, that is, between +128 and 255. Without a locale specified, unlike all other characters or +code points, these characters can have very different semantics +depending on the rules in effect. (Characters whose code points are +above 255 force Unicode rules; whereas the rules for ASCII characters +are the same under both ASCII and Unicode rules.) + +Under Unicode rules, these upper-Latin1 characters are interpreted as +Unicode code points, which means they have the same semantics as Latin-1 +(ISO-8859-1) and C1 controls. + +As explained in L</ASCII Rules versus Unicode Rules>, under ASCII rules, +they are considered to be unassigned characters. + +This can lead to unexpected results. For example, a string's +semantics can suddenly change if a code point above 255 is appended to +it, which changes the rules from ASCII to Unicode. As an +example, consider the following program and its output: + + $ perl -le' + no feature 'unicode_strings'; + $s1 = "\xC2"; + $s2 = "\x{2660}"; + for ($s1, $s2, $s1.$s2) { + print /\w/ || 0; + } + ' + 0 + 0 + 1 + +If there's no C<\w> in C<s1> nor in C<s2>, why does their concatenation +have one? + +This anomaly stems from Perl's attempt to not disturb older programs that +didn't use Unicode, along with Perl's desire to add Unicode support +seamlessly. But the result turned out to not be seamless. (By the way, +you can choose to be warned when things like this happen. See +C<L<encoding::warnings>>.) + +L<S<C<use feature 'unicode_strings'>>|feature/The 'unicode_strings' feature> +was added, starting in Perl v5.12, to address this problem. It affects +these things: =over 4 @@ -1610,79 +1737,63 @@ The old, problematic behavior affects these areas: Changing the case of a scalar, that is, using C<uc()>, C<ucfirst()>, C<lc()>, and C<lcfirst()>, or C<\L>, C<\U>, C<\u> and C<\l> in double-quotish contexts, such as regular expression substitutions. -Under C<unicode_strings> starting in Perl 5.12.0, character semantics are + +Under C<unicode_strings> starting in Perl 5.12.0, Unicode rules are generally used. See L<perlfunc/lc> for details on how this works in combination with various other pragmas. =item * Using caseless (C</i>) regular expression matching. + Starting in Perl 5.14.0, regular expressions compiled within -the scope of C<unicode_strings> use character semantics +the scope of C<unicode_strings> use Unicode rules even when executed or compiled into larger regular expressions outside the scope. =item * -Matching any of several properties in regular expressions, namely -C<\b> (without braces), C<\B> (without braces), C<\s>, C<\S>, C<\w>, -C<\W>, and all the Posix character classes +Matching any of several properties in regular expressions. + +These properties are C<\b> (without braces), C<\B> (without braces), +C<\s>, C<\S>, C<\w>, C<\W>, and all the Posix character classes I<except> C<[[:ascii:]]>. + Starting in Perl 5.14.0, regular expressions compiled within -the scope of C<unicode_strings> use character semantics +the scope of C<unicode_strings> use Unicode rules even when executed or compiled into larger regular expressions outside the scope. =item * -In C<quotemeta> or its inline equivalent C<\Q>, no code points above 127 -are quoted in UTF-8 encoded strings, but in byte encoded strings, code -points between 128-255 are always quoted. +In C<quotemeta> or its inline equivalent C<\Q>. + Starting in Perl 5.16.0, consistent quoting rules are used within the scope of C<unicode_strings>, as described in L<perlfunc/quotemeta>. +Prior to that, or outside its scope, no code points above 127 are quoted +in UTF-8 encoded strings, but in byte encoded strings, code points +between 128-255 are always quoted. =back -This behavior can lead to unexpected results in which a string's semantics -suddenly change if a code point above 255 is appended to or removed from it, -which changes the string's semantics from byte to character or vice versa. As -an example, consider the following program and its output: - - $ perl -le' - no feature 'unicode_strings'; - $s1 = "\xC2"; - $s2 = "\x{2660}"; - for ($s1, $s2, $s1.$s2) { - print /\w/ || 0; - } - ' - 0 - 0 - 1 - -If there's no C<\w> in C<s1> or in C<s2>, why does their concatenation have one? - -This anomaly stems from Perl's attempt to not disturb older programs that -didn't use Unicode, and hence had no semantics for characters outside of the -ASCII range (except in a locale), along with Perl's desire to add Unicode -support seamlessly. The result wasn't seamless: these characters were -orphaned. +You can see from the above that the effect of C<unicode_strings> +increased over several Perl releases. (And Perl's support for Unicode +continues to improve; it's best to use the latest available release in +order to get the most complete and accurate results possible.) Note that +C<unicode_strings> is automatically chosen if you S<C<use 5.012>> or +higher. For Perls earlier than those described above, or when a string is passed -to a function outside the subpragma's scope, a workaround is to always -call L<C<utf8::upgrade($string)>|utf8/Utility functions>, -or to use the standard module L<Encode>. Also, a scalar that has any characters -whose ordinal is C<0x100> or above, or which were specified using either of the -C<\N{...}> notations, will automatically have character semantics. +to a function outside the scope of C<unicode_strings>, see the next section. =head2 Forcing Unicode in Perl (Or Unforcing Unicode in Perl) Sometimes (see L</"When Unicode Does Not Happen"> or L</The "Unicode Bug">) there are situations where you simply need to force a byte -string into UTF-8, or vice versa. The low-level calls +string into UTF-8, or vice versa. The standard module L<Encode> can be +used for this, or the low-level calls L<C<utf8::upgrade($bytestring)>|utf8/Utility functions> and -L<C<utf8::downgrade($utf8string[, FAIL_OK])>|utf8/Utility functions> are -the answers. +L<C<utf8::downgrade($utf8string[, FAIL_OK])>|utf8/Utility functions>. Note that C<utf8::downgrade()> can fail if the string contains characters that don't fit into a byte. @@ -1690,118 +1801,20 @@ that don't fit into a byte. Calling either function on a string that already is in the desired state is a no-op. -=head2 Using Unicode in XS - -If you want to handle Perl Unicode in XS extensions, you may find the -following C APIs useful. See also L<perlguts/"Unicode Support"> for an -explanation about Unicode at the XS level, and L<perlapi> for the API -details. - -=over 4 - -=item * - -C<DO_UTF8(sv)> returns true if the C<UTF8> flag is on and the bytes -pragma is not in effect. C<SvUTF8(sv)> returns true if the C<UTF8> -flag is on; the C<bytes> pragma is ignored. The C<UTF8> flag being on -does B<not> mean that there are any characters of code points greater -than 255 (or 127) in the scalar or that there are even any characters -in the scalar. What the C<UTF8> flag means is that the sequence of -octets in the representation of the scalar is the sequence of UTF-8 -encoded code points of the characters of a string. The C<UTF8> flag -being off means that each octet in this representation encodes a -single character with code point 0..255 within the string. Perl's -Unicode model is not to use UTF-8 until it is absolutely necessary. - -=item * - -C<uvchr_to_utf8(buf, chr)> writes a Unicode character code point into -a buffer encoding the code point as UTF-8, and returns a pointer -pointing after the UTF-8 bytes. It works appropriately on EBCDIC machines. - -=item * - -C<utf8_to_uvchr_buf(buf, bufend, lenp)> reads UTF-8 encoded bytes from a -buffer and -returns the Unicode character code point and, optionally, the length of -the UTF-8 byte sequence. It works appropriately on EBCDIC machines. - -=item * - -C<utf8_length(start, end)> returns the length of the UTF-8 encoded buffer -in characters. C<sv_len_utf8(sv)> returns the length of the UTF-8 encoded -scalar. - -=item * - -C<sv_utf8_upgrade(sv)> converts the string of the scalar to its UTF-8 -encoded form. C<sv_utf8_downgrade(sv)> does the opposite, if -possible. C<sv_utf8_encode(sv)> is like sv_utf8_upgrade except that -it does not set the C<UTF8> flag. C<sv_utf8_decode()> does the -opposite of C<sv_utf8_encode()>. Note that none of these are to be -used as general-purpose encoding or decoding interfaces: C<use Encode> -for that. C<sv_utf8_upgrade()> is affected by the encoding pragma -but C<sv_utf8_downgrade()> is not (since the encoding pragma is -designed to be a one-way street). +L</ASCII Rules versus Unicode Rules> gives all the ways that a string is +made to use Unicode rules. -=item * - -C<is_utf8_string(buf, len)> returns true if C<len> bytes of the buffer -are valid UTF-8. - -=item * - -C<isUTF8_CHAR(buf, buf_end)> returns true if the pointer points to -a valid UTF-8 character. - -=item * - -C<UTF8SKIP(buf)> will return the number of bytes in the UTF-8 encoded -character in the buffer. C<UNISKIP(chr)> will return the number of bytes -required to UTF-8-encode the code point. C<UTF8SKIP()> -is useful for example for iterating over the characters of a UTF-8 -encoded buffer; C<UNISKIP()> is useful, for example, in computing -the size required for a UTF-8 encoded buffer. - -=item * - -C<utf8_distance(a, b)> will tell the distance in characters between the -two pointers pointing to the same UTF-8 encoded buffer. - -=item * - -C<utf8_hop(s, off)> will return a pointer to a UTF-8 encoded buffer -that is C<off> (positive or negative) Unicode characters displaced -from the UTF-8 buffer C<s>. Be careful not to overstep the buffer: -C<utf8_hop()> will merrily run off the end or the beginning of the -buffer if told to do so. - -=item * - -C<pv_uni_display(dsv, spv, len, pvlim, flags)> and -C<sv_uni_display(dsv, ssv, pvlim, flags)> are useful for debugging the -output of Unicode strings and scalars. By default they are useful -only for debugging--they display B<all> characters as hexadecimal code -points--but with the flags C<UNI_DISPLAY_ISPRINT>, -C<UNI_DISPLAY_BACKSLASH>, and C<UNI_DISPLAY_QQ> you can make the -output more readable. - -=item * - -C<foldEQ_utf8(s1, pe1, l1, u1, s2, pe2, l2, u2)> can be used to -compare two strings case-insensitively in Unicode. For case-sensitive -comparisons you can just use C<memEQ()> and C<memNE()> as usual, except -if one string is in utf8 and the other isn't. - -=back +=head2 Using Unicode in XS -For more information, see L<perlapi>, and F<utf8.c> and F<utf8.h> -in the Perl source code distribution. +See L<perlguts/"Unicode Support"> for an introduction to Unicode at +the XS level, and L<perlapi/Unicode Support> for the API details. =head2 Hacking Perl to work on earlier Unicode versions (for very serious hackers only) -Perl by default comes with the latest supported Unicode version built in, but -you can change to use any earlier one. +Perl by default comes with the latest supported Unicode version built-in, but +the goal is to allow you to change to use any earlier one. In Perls +v5.20 and v5.22, however, the earliest usable version is Unicode 5.1. +Perl v5.18 is able to handle all earlier versions. Download the files in the desired version of Unicode from the Unicode web site L<http://www.unicode.org>). These should replace the existing files in @@ -1809,118 +1822,15 @@ F<lib/unicore> in the Perl source tree. Follow the instructions in F<README.perl> in that directory to change some of their names, and then build perl (see L<INSTALL>). -=head1 BUGS - -=head2 Interaction with Locales - -See L<perllocale/Unicode and UTF-8> - -=head2 Problems with characters in the Latin-1 Supplement range - -See L</The "Unicode Bug"> - -=head2 Interaction with Extensions - -When Perl exchanges data with an extension, the extension should be -able to understand the UTF8 flag and act accordingly. If the -extension doesn't recognize that flag, it's likely that the extension -will return incorrectly-flagged data. - -So if you're working with Unicode data, consult the documentation of -every module you're using if there are any issues with Unicode data -exchange. If the documentation does not talk about Unicode at all, -suspect the worst and probably look at the source to learn how the -module is implemented. Modules written completely in Perl shouldn't -cause problems. Modules that directly or indirectly access code written -in other programming languages are at risk. - -For affected functions, the simple strategy to avoid data corruption is -to always make the encoding of the exchanged data explicit. Choose an -encoding that you know the extension can handle. Convert arguments passed -to the extensions to that encoding and convert results back from that -encoding. Write wrapper functions that do the conversions for you, so -you can later change the functions when the extension catches up. - -To provide an example, let's say the popular C<Foo::Bar::escape_html> -function doesn't deal with Unicode data yet. The wrapper function -would convert the argument to raw UTF-8 and convert the result back to -Perl's internal representation like so: - - sub my_escape_html ($) { - my($what) = shift; - return unless defined $what; - Encode::decode_utf8(Foo::Bar::escape_html( - Encode::encode_utf8($what))); - } - -Sometimes, when the extension does not convert data but just stores -and retrieves them, you will be able to use the otherwise -dangerous L<C<Encode::_utf8_on()>|Encode/_utf8_on> function. Let's say -the popular C<Foo::Bar> extension, written in C, provides a C<param> -method that lets you store and retrieve data according to these prototypes: - - $self->param($name, $value); # set a scalar - $value = $self->param($name); # retrieve a scalar - -If it does not yet provide support for any encoding, one could write a -derived class with such a C<param> method: - - sub param { - my($self,$name,$value) = @_; - utf8::upgrade($name); # make sure it is UTF-8 encoded - if (defined $value) { - utf8::upgrade($value); # make sure it is UTF-8 encoded - return $self->SUPER::param($name,$value); - } else { - my $ret = $self->SUPER::param($name); - Encode::_utf8_on($ret); # we know, it is UTF-8 encoded - return $ret; - } - } - -Some extensions provide filters on data entry/exit points, such as -C<DB_File::filter_store_key> and family. Look out for such filters in -the documentation of your extensions, they can make the transition to -Unicode data much easier. - -=head2 Speed - -Some functions are slower when working on UTF-8 encoded strings than -on byte encoded strings. All functions that need to hop over -characters such as C<length()>, C<substr()> or C<index()>, or matching -regular expressions can work B<much> faster when the underlying data are -byte-encoded. - -In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1 -a caching scheme was introduced which will hopefully make the slowness -somewhat less spectacular, at least for some operations. In general, -operations with UTF-8 encoded strings are still slower. As an example, -the Unicode properties (character classes) like C<\p{Nd}> are known to -be quite a bit slower (5-20 times) than their simpler counterparts -like C<\d> (then again, there are hundreds of Unicode characters matching C<Nd> -compared with the 10 ASCII characters matching C<d>). - -=head2 Problems on EBCDIC platforms - -There are several known problems with Perl on EBCDIC platforms. If you -want to use Perl there, send email to [email protected]. - -In earlier versions, when byte and character data were concatenated, -the new string was sometimes created by -decoding the byte strings as I<ISO 8859-1 (Latin-1)>, even if the -old Unicode string used EBCDIC. - -If you find any of these, please report them as bugs. - =head2 Porting code from perl-5.6.X -Perl 5.8 has a different Unicode model from 5.6. In 5.6 the programmer -was required to use the C<utf8> pragma to declare that a given scope -expected to deal with Unicode data and had to make sure that only -Unicode data were reaching that scope. If you have code that is +Perls starting in 5.8 have a different Unicode model from 5.6. In 5.6 the +programmer was required to use the C<utf8> pragma to declare that a +given scope expected to deal with Unicode data and had to make sure that +only Unicode data were reaching that scope. If you have code that is working with 5.6, you will need some of the following adjustments to -your code. The examples are written such that the code will continue -to work under 5.6, so you should be safe to try them out. +your code. The examples are written such that the code will continue to +work under 5.6, so you should be safe to try them out. =over 3 @@ -2023,10 +1933,94 @@ the UTF8 flag: =back +=head1 BUGS + +See also L</The "Unicode Bug"> above. + +=head2 Interaction with Extensions + +When Perl exchanges data with an extension, the extension should be +able to understand the UTF8 flag and act accordingly. If the +extension doesn't recognize that flag, it's likely that the extension +will return incorrectly-flagged data. + +So if you're working with Unicode data, consult the documentation of +every module you're using if there are any issues with Unicode data +exchange. If the documentation does not talk about Unicode at all, +suspect the worst and probably look at the source to learn how the +module is implemented. Modules written completely in Perl shouldn't +cause problems. Modules that directly or indirectly access code written +in other programming languages are at risk. + +For affected functions, the simple strategy to avoid data corruption is +to always make the encoding of the exchanged data explicit. Choose an +encoding that you know the extension can handle. Convert arguments passed +to the extensions to that encoding and convert results back from that +encoding. Write wrapper functions that do the conversions for you, so +you can later change the functions when the extension catches up. + +To provide an example, let's say the popular C<Foo::Bar::escape_html> +function doesn't deal with Unicode data yet. The wrapper function +would convert the argument to raw UTF-8 and convert the result back to +Perl's internal representation like so: + + sub my_escape_html ($) { + my($what) = shift; + return unless defined $what; + Encode::decode_utf8(Foo::Bar::escape_html( + Encode::encode_utf8($what))); + } + +Sometimes, when the extension does not convert data but just stores +and retrieves it, you will be able to use the otherwise +dangerous L<C<Encode::_utf8_on()>|Encode/_utf8_on> function. Let's say +the popular C<Foo::Bar> extension, written in C, provides a C<param> +method that lets you store and retrieve data according to these prototypes: + + $self->param($name, $value); # set a scalar + $value = $self->param($name); # retrieve a scalar + +If it does not yet provide support for any encoding, one could write a +derived class with such a C<param> method: + + sub param { + my($self,$name,$value) = @_; + utf8::upgrade($name); # make sure it is UTF-8 encoded + if (defined $value) { + utf8::upgrade($value); # make sure it is UTF-8 encoded + return $self->SUPER::param($name,$value); + } else { + my $ret = $self->SUPER::param($name); + Encode::_utf8_on($ret); # we know, it is UTF-8 encoded + return $ret; + } + } + +Some extensions provide filters on data entry/exit points, such as +C<DB_File::filter_store_key> and family. Look out for such filters in +the documentation of your extensions; they can make the transition to +Unicode data much easier. + +=head2 Speed + +Some functions are slower when working on UTF-8 encoded strings than +on byte encoded strings. All functions that need to hop over +characters such as C<length()>, C<substr()> or C<index()>, or matching +regular expressions can work B<much> faster when the underlying data are +byte-encoded. + +In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1 +a caching scheme was introduced which improved the situation. In general, +operations with UTF-8 encoded strings are still slower. As an example, +the Unicode properties (character classes) like C<\p{Nd}> are known to +be quite a bit slower (5-20 times) than their simpler counterparts +like C<[0-9]> (then again, there are hundreds of Unicode characters matching +C<Nd> compared with the 10 ASCII characters matching C<[0-9]>). + =head1 SEE ALSO L<perlunitut>, L<perluniintro>, L<perluniprops>, L<Encode>, L<open>, L<utf8>, L<bytes>, -L<perlretut>, L<perlvar/"${^UNICODE}"> +L<perlretut>, L<perlvar/"${^UNICODE}">, L<http://www.unicode.org/reports/tr44>). =cut diff --git a/pod/perluniintro.pod b/pod/perluniintro.pod index 7a87874..7ddf77c 100644 --- a/pod/perluniintro.pod +++ b/pod/perluniintro.pod @@ -638,14 +638,17 @@ character classes that are Unicode-aware. There are dozens of them, see L<perluniprops>. Starting in v5.22, you can use Unicode code points as the end points of -character ranges, and the range will include all Unicode code points -that lie between those end points, inclusive. +regular expression pattern character ranges, and the range will include +all Unicode code points that lie between those end points, inclusive. qr/ [\N{U+03]-\N{U+20}] /x includes the code points C<\N{U+03}>, C<\N{U+04}>, ..., C<\N{U+20}>. +(It is planned to extend this behavior to ranges in C<tr///> in Perl +v5.24.) + =item * String-To-Number Conversions diff --git a/pod/perlunitut.pod b/pod/perlunitut.pod index 0ac91e0..e96a9d2 100644 --- a/pod/perlunitut.pod +++ b/pod/perlunitut.pod @@ -179,7 +179,8 @@ data.) =head1 Q and A (or FAQ) -After reading this document, you ought to read L<perlunifaq> too. +After reading this document, you ought to read L<perlunifaq> too, then +L<perluniintro>. =head1 ACKNOWLEDGEMENTS diff --git a/utf8.h b/utf8.h index 73e9588..3e15707 100644 --- a/utf8.h +++ b/utf8.h @@ -41,6 +41,12 @@ /* =head1 Unicode Support +L<perlguts/Unicode Support> has an introduction to this API. + +See also L</Character classification>, +and L</Character case changing>. +Various functions outside this section also work specially with Unicode. +Search for the string "utf8" in this document. =for apidoc is_ascii_string @@ -324,11 +330,22 @@ Perl's extended UTF-8 means we can have start bytes up to FF. **** PATCH TRUNCATED AT 2000 LINES -- 60 NOT SHOWN **** -- Perl5 Master Repository
