Update the Mac OS X situation.
[p5sagit/p5-mst-13.2.git] / pod / perluniintro.pod
index 1d4162b..d6eae60 100644 (file)
@@ -51,18 +51,19 @@ more I<modifiers> (like C<COMBINING ACUTE ACCENT>).  This sequence of
 a base character and modifiers is called a I<combining character
 sequence>.
 
-Whether to call these combining character sequences, as a whole,            
-"characters" depends on your point of view. If you are a programmer, you     
-probably would tend towards seeing each element in the sequences as one
-unit, one "character", but from the user viewpoint, the sequence as a
-whole is probably considered one "character", since that's probably what   
-it looks like in the context of the user's language.
+Whether to call these combining character sequences, as a whole,
+"characters" depends on your point of view. If you are a programmer,
+you probably would tend towards seeing each element in the sequences
+as one unit, one "character", but from the user viewpoint, the
+sequence as a whole is probably considered one "character", since
+that's probably what it looks like in the context of the user's
+language.
 
 With this "as a whole" view of characters, the number of characters is
-open-ended. But in the programmer's "one unit is one character" point of
-view, the concept of "characters" is more deterministic, and so we take
-that point of view in this document: one "character" is one Unicode
-code point, be it a base character or a combining character.
+open-ended. But in the programmer's "one unit is one character" point
+of view, the concept of "characters" is more deterministic, and so we
+take that point of view in this document: one "character" is one
+Unicode code point, be it a base character or a combining character.
 
 For some of the combinations there are I<precomposed> characters,
 for example C<LATIN CAPITAL LETTER A WITH ACUTE> is defined as
@@ -126,8 +127,8 @@ that operations in the current block or file would be Unicode-aware.
 This model was found to be wrong, or at least clumsy: the Unicodeness
 is now carried with the data, not attached to the operations.  (There
 is one remaining case where an explicit C<use utf8> is needed: if your
-Perl script itself is encoded in UTF-8, you can use UTF-8 in your variable and
-subroutine names, and in your string and regular expression literals,
+Perl script itself is encoded in UTF-8, you can use UTF-8 in your
+identifier names, and in your string and regular expression literals,
 by saying C<use utf8>.  This is not the default because that would
 break existing scripts having legacy 8-bit data in them.)
 
@@ -142,19 +143,20 @@ transparently upgraded to Unicode.
 Internally, Perl currently uses either whatever the native eight-bit
 character set of the platform (for example Latin-1) or UTF-8 to encode
 Unicode strings. Specifically, if all code points in the string are
-0xFF or less, Perl uses the native eight-bit character set.  Otherwise, it uses UTF-8.
+0xFF or less, Perl uses the native eight-bit character set.
+Otherwise, it uses UTF-8.
 
-A user of Perl does not normally need to know nor care how Perl happens
-to encodes its internal strings, but it becomes relevant when outputting
-Unicode strings to a stream without a discipline (one with the "default
-default").  In such a case, the raw bytes used internally (the native
-character set or UTF-8, as appropriate for each string) will be used,
-and if warnings are turned on, a "Wide character" warning will be issued
-if those strings contain a character beyond 0x00FF.
+A user of Perl does not normally need to know nor care how Perl
+happens to encode its internal strings, but it becomes relevant when
+outputting Unicode strings to a stream without a discipline (one with
+the "default default").  In such a case, the raw bytes used internally
+(the native character set or UTF-8, as appropriate for each string)
+will be used, and a "Wide character" warning will be issued if those
+strings contain a character beyond 0x00FF.
 
 For example,
 
-      perl -w -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"'              
+      perl -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"'              
 
 produces a fairly useless mixture of native bytes and UTF-8, as well
 as a warning.
@@ -166,20 +168,32 @@ To output UTF-8 always, use the ":utf8" output discipline.  Prepending
 to this sample program ensures the output is completely UTF-8, and      
 of course, removes the warning.
 
-Perl 5.8.0 also supports Unicode on EBCDIC platforms.  There, the
-support is somewhat harder to implement since additional conversions
-are needed at every step.  Because of these difficulties, the Unicode
-support isn't quite as full as in other, mainly ASCII-based,
-platforms (the Unicode support is better than in the 5.6 series,
-which didn't work much at all for EBCDIC platform).  On EBCDIC
-platforms, the internal Unicode encoding form is UTF-EBCDIC instead
-of UTF-8 (the difference is that as UTF-8 is "ASCII-safe" in that
-ASCII characters encode to UTF-8 as-is, UTF-EBCDIC is "EBCDIC-safe").
+If your locale environment variables (LANGUAGE, LC_ALL, LC_CTYPE, LANG)
+contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
+the default encoding of your STDIN, STDOUT, and STDERR, and of
+B<any subsequent file open>, is UTF-8.  Note that this means
+that Perl expects other software to work, too: if STDIN coming
+in from another command is not UTF-8, Perl will complain about
+malformed UTF-8.
+
+=head2 Unicode and EBCDIC
+
+Perl 5.8.0 also supports Unicode on EBCDIC platforms.  There,
+the Unicode support is somewhat more complex to implement since
+additional conversions are needed at every step.  Some problems
+remain, see L<perlebcdic> for details.
+
+In any case, the Unicode support on EBCDIC platforms is better than
+in the 5.6 series, which didn't work much at all for EBCDIC platform.
+On EBCDIC platforms, the internal Unicode encoding form is UTF-EBCDIC
+instead of UTF-8 (the difference is that as UTF-8 is "ASCII-safe" in
+that ASCII characters encode to UTF-8 as-is, UTF-EBCDIC is
+"EBCDIC-safe").
 
 =head2 Creating Unicode
 
-To create Unicode characters in literals for code points above 0xFF, use the
-C<\x{...}> notation in doublequoted strings:
+To create Unicode characters in literals for code points above 0xFF,
+use the C<\x{...}> notation in doublequoted strings:
 
     my $smiley = "\x{263a}";
 
@@ -195,13 +209,13 @@ At run-time you can use C<chr()>:
 
 Naturally, C<ord()> will do the reverse: turn a character to a code point.
 
-Note that C<\x..> (no C<{}> and only two hexadecimal digits), C<\x{...}>,
-and C<chr(...)> for arguments less than 0x100 (decimal 256)
-generate an eight-bit character for backward compatibility with older
-Perls.  For arguments of 0x100 or more, Unicode characters are always
-produced. If you want to force the production of Unicode characters
-regardless of the numeric value, use C<pack("U", ...)> instead of C<\x..>,
-C<\x{...}>, or C<chr()>.
+Note that C<\x..> (no C<{}> and only two hexadecimal digits),
+C<\x{...}>, and C<chr(...)> for arguments less than 0x100 (decimal
+256) generate an eight-bit character for backward compatibility with
+older Perls.  For arguments of 0x100 or more, Unicode characters are
+always produced. If you want to force the production of Unicode
+characters regardless of the numeric value, use C<pack("U", ...)>
+instead of C<\x..>, C<\x{...}>, or C<chr()>.
 
 You can also use the C<charnames> pragma to invoke characters
 by name in doublequoted strings:
@@ -218,6 +232,17 @@ Note that both C<\x{...}> and C<\N{...}> are compile-time string
 constants: you cannot use variables in them.  if you want similar
 run-time functionality, use C<chr()> and C<charnames::vianame()>.
 
+Also note that if all the code points for pack "U" are below 0x100,
+bytes will be generated, just like if you were using C<chr()>.
+
+   my $bytes = pack("U*", 0x80, 0xFF);
+
+If you want to force the result to Unicode characters, use the special
+C<"U0"> prefix.  It consumes no arguments but forces the result to be
+in Unicode characters, instead of bytes.
+
+   my $chars = pack("U0U*", 0x80, 0xFF);
+
 =head2 Handling Unicode
 
 Handling Unicode is for the most part transparent: just use the
@@ -254,8 +279,8 @@ C<Latin 2>, or C<iso8859-2>, and so forth.  With just
 
     use encoding;
 
-first the environment variable C<PERL_ENCODING> will be consulted,
-and if that doesn't exist, ISO 8859-1 (Latin 1) will be assumed.
+the environment variable C<PERL_ENCODING> will be consulted,
+but if that doesn't exist, the encoding pragma fails.
 
 The C<Encode> module knows about many encodings and it has interfaces
 for doing conversions between those encodings:
@@ -270,11 +295,11 @@ Normally, writing out Unicode data
     print FH $some_string_with_unicode, "\n";
 
 produces raw bytes that Perl happens to use to internally encode the
-Unicode string (which depends on the system, as well as what characters
-happen to be in the string at the time). If any of the characters are at
-code points 0x100 or above, you will get a warning if you use C<-w> or C<use
-warnings>. To ensure that the output is explicitly rendered in the encoding
-you desire (and to avoid the warning), open the stream with the desired
+Unicode string (which depends on the system, as well as what
+characters happen to be in the string at the time). If any of the
+characters are at code points 0x100 or above, you will get a warning.
+To ensure that the output is explicitly rendered in the encoding you
+desire (and to avoid the warning), open the stream with the desired
 encoding. Some examples:
 
     open FH, ">:ucs2",      "file"
@@ -289,9 +314,10 @@ and on already open streams use C<binmode()>:
 
 See documentation for the C<Encode> module for many supported encodings.
 
-Reading in a file that you know happens to be encoded in one of the Unicode
-encodings does not magically turn the data into Unicode in Perl's eyes.
-To do that, specify the appropriate discipline when opening files
+Reading in a file that you know happens to be encoded in one of the
+Unicode encodings does not magically turn the data into Unicode in
+Perl's eyes.  To do that, specify the appropriate discipline when
+opening files
 
     open(my $fh,'<:utf8', 'anything');
     my $line_of_unicode = <$fh>;
@@ -329,7 +355,7 @@ or you can also use the C<':encoding(...)'> discipline
 
 These methods install a transparent filter on the I/O stream that
 converts data from the specified encoding when it is read in from the
-stream. The result is always Unicode
+stream.  The result is always Unicode.
 
 The L<open> pragma affects all the C<open()> calls after the pragma by
 setting default disciplines.  If you want to affect only certain
@@ -344,10 +370,10 @@ C<:utf8> and C<:encoding(...)> methods do work with all of C<open()>,
 C<binmode()>, and the C<open> pragma.
 
 Similarly, you may use these I/O disciplines on output streams to
-automatically convert Unicode to the specified encoding when it is written
-to the stream. For example, the following snippet copies the contents of
-the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to the file
-"text.utf8", encoded as UTF-8:
+automatically convert Unicode to the specified encoding when it is
+written to the stream. For example, the following snippet copies the
+contents of the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to
+the file "text.utf8", encoded as UTF-8:
 
     open(my $nihongo, '<:encoding(iso2022-jp)', 'text.jis');
     open(my $unicode, '>:utf8',                 'text.utf8');
@@ -422,22 +448,23 @@ returns:
 
 Bit Complement Operator ~ And vec()
 
-The bit complement operator C<~> may produce surprising results if
-used on strings containing Unicode characters.  The results are
-consistent with the internal encoding of the characters, but not
-with much else.  So don't do that.  Similarly for vec(): you will be
-operating on the internally encoded bit patterns of the Unicode characters, not on
-the code point values, which is very probably not what you want.
+The bit complement operator C<~> may produce surprising results if used on
+strings containing characters with ordinal values above 255. In such a
+case, the results are consistent with the internal encoding of the
+characters, but not with much else. So don't do that. Similarly for vec():
+you will be operating on the internally encoded bit patterns of the Unicode
+characters, not on the code point values, which is very probably not what
+you want.
 
 =item *
 
 Peeking At Perl's Internal Encoding
 
 Normal users of Perl should never care how Perl encodes any particular
-Unicode string (because the normal ways to get at the contents of a string
-with Unicode -- via input and output -- should always be via
-explicitly-defined I/O disciplines). But if you must, there are two ways of
-looking behind the scenes.
+Unicode string (because the normal ways to get at the contents of a
+string with Unicode -- via input and output -- should always be via
+explicitly-defined I/O disciplines). But if you must, there are two
+ways of looking behind the scenes.
 
 One way of peeking inside the internal encoding of Unicode characters
 is to use C<unpack("C*", ...> to get the bytes, or C<unpack("H*", ...)>
@@ -470,9 +497,9 @@ in Unicode: what do you mean by equal?
 (Is C<LATIN CAPITAL LETTER A WITH ACUTE> equal to
 C<LATIN CAPITAL LETTER A>?)
 
-The short answer is that by default Perl compares equivalence
-(C<eq>, C<ne>) based only on code points of the characters.
-In the above case, the answer is no (because 0x00C1 != 0x0041).  But sometimes any
+The short answer is that by default Perl compares equivalence (C<eq>,
+C<ne>) based only on code points of the characters.  In the above
+case, the answer is no (because 0x00C1 != 0x0041).  But sometimes any
 CAPITAL LETTER As being considered equal, or even any As of any case,
 would be desirable.
 
@@ -513,19 +540,20 @@ http://www.unicode.org/unicode/reports/tr10/
 
 =item *
 
-Character Ranges
+Character Ranges and Classes
 
 Character ranges in regular expression character classes (C</[a-z]/>)
 and in the C<tr///> (also known as C<y///>) operator are not magically
 Unicode-aware.  What this means that C<[A-Za-z]> will not magically start
 to mean "all alphabetic letters" (not that it does mean that even for
-8-bit characters, you should be using C</[[:alpha]]/> for that).
+8-bit characters, you should be using C</[[:alpha:]]/> for that).
 
-For specifying things like that in regular expressions, you can use the
-various Unicode properties, C<\pL> or perhaps C<\p{Alphabetic}>, in this particular case.  You can
-use Unicode code points as the end points of character ranges, but
-that means that particular code point range, nothing more.  For
-further information, see L<perlunicode>.
+For specifying things like that in regular expressions, you can use
+the various Unicode properties, C<\pL> or perhaps C<\p{Alphabetic}>,
+in this particular case.  You can use Unicode code points as the end
+points of character ranges, but that means that particular code point
+range, nothing more.  For further information (there are dozens
+of Unicode character classes), see L<perlunicode>.
 
 =item *
 
@@ -542,7 +570,9 @@ than ASCII 0 to 9 (and ASCII a to f for hexadecimal).
 
 =over 4
 
-=item Will My Old Scripts Break?
+=item 
+
+Will My Old Scripts Break?
 
 Very probably not.  Unless you are generating Unicode characters
 somehow, any old behaviour should be preserved.  About the only
@@ -551,33 +581,17 @@ is the old behaviour of C<chr()> where supplying an argument more
 than 255 produced a character modulo 255 (for example, C<chr(300)>
 was equal to C<chr(45)>).
 
-=item How Do I Make My Scripts Work With Unicode?
+=item 
+
+How Do I Make My Scripts Work With Unicode?
 
 Very little work should be needed since nothing changes until you
 somehow generate Unicode data.  The greatest trick will be getting
 input as Unicode, and for that see the earlier I/O discussion.
 
-=item How Do I Know Whether My String Is In Unicode?
-
-  @@|  Note to P5P -- I see two problems with this section. One is
-  @@|  that Encode::is_utf8() really should be named
-  @@|  Encode::is_Unicode(), since that's what it's telling you,
-  @@|  isn't it? This
-  @@|        Encode::is_utf8(pack("U"), 0xDF)
-  @@|  returns true, even though the string being checked is
-  @@|  internally kept in the native 8-bit encoding, but flagged as
-  @@|  Unicode.
-  @@|  
-  @@|  Another problem is that yeah, I can see situations where
-  @@|  someone wants to know if a string is Unicode, or if it's
-  @@|  still in the native 8-bit encoding. What's wrong with that?
-  @@|  Perhaps when this section was added, it was with the that
-  @@|  that users don't need to care the particular encoding used
-  @@|  internally, and that's still the case (except for efficiency
-  @@|  issues -- reading utf8 is likely much faster than reading,
-  @@|  say, Shift-JIS).
-  @@|
-  @@|  Can is_utf8 be renamed to is_Unicode()?
+=item 
+
+How Do I Know Whether My String Is In Unicode?
 
 You shouldn't care.  No, you really shouldn't.  If you have
 to care (beyond the cases described above), it means that we
@@ -593,20 +607,37 @@ string are necessary UTF-8 encoded, or that any of the characters have
 code points greater than 0xFF (255) or even 0x80 (128), or that the
 string has any characters at all.  All the C<is_utf8()> does is to
 return the value of the internal "utf8ness" flag attached to the
-$string.  If the flag is on, characters added to that string will be
-automatically upgraded to UTF-8 (and even then only if they really
-need to be upgraded, that is, if their code point is greater than 0xFF).
+$string.  If the flag is off, the bytes in the scalar are interpreted
+as a single byte encoding.  If the flag is on, the bytes in the scalar
+are interpreted as the (multibyte, variable-length) UTF-8 encoded code
+points of the characters.  Bytes added to an UTF-8 encoded string are
+automatically upgraded to UTF-8.  If mixed non-UTF8 and UTF-8 scalars
+are merged (doublequoted interpolation, explicit concatenation, and
+printf/sprintf parameter substitution), the result will be UTF-8 encoded
+as if copies of the byte strings were upgraded to UTF-8: for example,
+
+    $a = "ab\x80c";
+    $b = "\x{100}";
+    print "$a = $b\n";
+
+the output string will be UTF-8-encoded "ab\x80c\x{100}\n", but note
+that C<$a> will stay single byte encoded.
 
 Sometimes you might really need to know the byte length of a string
-instead of the character length.  For that use the C<bytes> pragma
-and its only defined function C<length()>:
+instead of the character length. For that use either the
+C<Encode::encode_utf8()> function or the C<bytes> pragma and its only
+defined function C<length()>:
 
     my $unicode = chr(0x100);
     print length($unicode), "\n"; # will print 1
+    require Encode;
+    print length(Encode::encode_utf8($unicode)), "\n"; # will print 2
     use bytes;
-    print length($unicode), "\n"; # will print 2 (the 0xC4 0x80 of the UTF-8)
+    print length($unicode), "\n"; # will also print 2 (the 0xC4 0x80 of the UTF-8)
+
+=item 
 
-=item How Do I Detect Data That's Not Valid In a Particular Encoding
+How Do I Detect Data That's Not Valid In a Particular Encoding?
 
 Use the C<Encode> package to try converting it.
 For example,
@@ -625,19 +656,22 @@ For UTF-8 only, you can use:
 
 If invalid, a C<Malformed UTF-8 character (byte 0x##) in
 unpack> is produced. The "U0" means "expect strictly UTF-8
-encoded Unicode". Without that the C<unpack("U*", ...)>
-would accept also data like C<chr(0xFF>).
+encoded Unicode".  Without that the C<unpack("U*", ...)>
+would accept also data like C<chr(0xFF>), similarly to the
+C<pack> as we saw earlier.
 
-=item How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa?
+=item 
+
+How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa?
 
 This probably isn't as useful as you might think.
 Normally, you shouldn't need to.
 
-In one sense, what you are asking doesn't make much sense: Encodings are
-for characters, and binary data is not "characters", so converting "data"
-into some encoding isn't meaningful unless you know in what character set
-and encoding the binary data is in, in which case it's not binary data, now
-is it?
+In one sense, what you are asking doesn't make much sense: Encodings
+are for characters, and binary data is not "characters", so converting
+"data" into some encoding isn't meaningful unless you know in what
+character set and encoding the binary data is in, in which case it's
+not binary data, now is it?
 
 If you have a raw sequence of bytes that you know should be interpreted via
 a particular encoding, you can use C<Encode>:
@@ -662,9 +696,9 @@ The contents of the string changes, but not the nature of the string.
 Perl doesn't know any more after the call than before that the contents
 of the string indicates the affirmative.
 
-Back to converting data, if you have (or want) data in your system's native
-8-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use pack/unpack to
-convert to/from Unicode.
+Back to converting data, if you have (or want) data in your system's
+native 8-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use
+pack/unpack to convert to/from Unicode.
 
     $native_string  = pack("C*", unpack("U*", $Unicode_string));
     $Unicode_string = pack("U*", unpack("C*", $native_string));
@@ -681,12 +715,16 @@ Any random collection of bytes isn't well-formed UTF-8.  You can
 use C<unpack("C*", $string)> for the former, and you can create
 well-formed Unicode data by C<pack("U*", 0xff, ...)>.
 
-=item How Do I Display Unicode?  How Do I Input Unicode?
+=item 
+
+How Do I Display Unicode?  How Do I Input Unicode?
 
 See http://www.hclrss.demon.co.uk/unicode/ and
 http://www.cl.cam.ac.uk/~mgk25/unicode.html
 
-=item How Does Unicode Work With Traditional Locales?
+=item 
+
+How Does Unicode Work With Traditional Locales?
 
 In Perl, not very well.  Avoid using locales through the C<locale>
 pragma.  Use only one or the other.
@@ -706,8 +744,7 @@ a-f (or A-F, case doesn't matter).  Each hexadecimal digit represents
 four bits, or half a byte.  C<print 0x..., "\n"> will show a
 hexadecimal number in decimal, and C<printf "%x\n", $decimal> will
 show a decimal number in hexadecimal.  If you have just the
-"hexdigits" of a hexadecimal number, you can use the C<hex()>
-function.
+"hexdigits" of a hexadecimal number, you can use the C<hex()> function.
 
     print 0x0009, "\n";    # 9
     print 0x000a, "\n";    # 10
@@ -783,7 +820,7 @@ in Perl 5.8.0 or newer, and
 
 in the Perl 5.6 series.  (The renaming to F<lib/unicore> was done to
 avoid naming conflicts with lib/Unicode in case-insensitive filesystems.)
-The main Unicode data file is F<Unicode.txt> (or F<Unicode.301> in
+The main Unicode data file is F<UnicodeData.txt> (or F<Unicode.301> in
 Perl 5.6.1.)  You can find the C<$Config{installprivlib}> by
 
     perl "-V:installprivlib"
@@ -806,6 +843,15 @@ C<Unicode::Map8>, and C<Unicode::Map>, available from CPAN.
 If you have the GNU recode installed, you can also use the
 Perl frontend C<Convert::Recode> for character conversions.
 
+The following are fast conversions from ISO 8859-1 (Latin-1) bytes
+to UTF-8 bytes, the code works even with older Perl 5 versions.
+
+    # ISO 8859-1 to UTF-8
+    s/([\x80-\xFF])/chr(0xC0|ord($1)>>6).chr(0x80|ord($1)&0x3F)/eg;
+
+    # UTF-8 to ISO 8859-1
+    s/([\xC2\xC3])([\x80-\xBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg;
+
 =head1 SEE ALSO
 
 L<perlunicode>, L<Encode>, L<encoding>, L<open>, L<utf8>, L<bytes>,
@@ -819,6 +865,6 @@ mailing lists for their valuable feedback.
 
 =head1 AUTHOR, COPYRIGHT, AND LICENSE
 
-Copyright 2001 Jarkko Hietaniemi <jhi@iki.fi>
+Copyright 2001-2002 Jarkko Hietaniemi <jhi@iki.fi>
 
 This document may be distributed under the same terms as Perl itself.