1N/A=head1 NAME
1N/A
1N/Aperluniintro - Perl Unicode introduction
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThis document gives a general idea of Unicode and how to use Unicode
1N/Ain Perl.
1N/A
1N/A=head2 Unicode
1N/A
1N/AUnicode is a character set standard which plans to codify all of the
1N/Awriting systems of the world, plus many other symbols.
1N/A
1N/AUnicode and ISO/IEC 10646 are coordinated standards that provide code
1N/Apoints for characters in almost all modern character set standards,
1N/Acovering more than 30 writing systems and hundreds of languages,
1N/Aincluding all commercially-important modern languages. All characters
1N/Ain the largest Chinese, Japanese, and Korean dictionaries are also
1N/Aencoded. The standards will eventually cover almost all characters in
1N/Amore than 250 writing systems and thousands of languages.
1N/AUnicode 1.0 was released in October 1991, and 4.0 in April 2003.
1N/A
1N/AA Unicode I<character> is an abstract entity. It is not bound to any
1N/Aparticular integer width, especially not to the C language C<char>.
1N/AUnicode is language-neutral and display-neutral: it does not encode the
1N/Alanguage of the text and it does not define fonts or other graphical
1N/Alayout details. Unicode operates on characters and on text built from
1N/Athose characters.
1N/A
1N/AUnicode defines characters like C<LATIN CAPITAL LETTER A> or C<GREEK
1N/ASMALL LETTER ALPHA> and unique numbers for the characters, in this
1N/Acase 0x0041 and 0x03B1, respectively. These unique numbers are called
1N/AI<code points>.
1N/A
1N/AThe Unicode standard prefers using hexadecimal notation for the code
1N/Apoints. If numbers like C<0x0041> are unfamiliar to you, take a peek
1N/Aat a later section, L</"Hexadecimal Notation">. The Unicode standard
1N/Auses the notation C<U+0041 LATIN CAPITAL LETTER A>, to give the
1N/Ahexadecimal code point and the normative name of the character.
1N/A
1N/AUnicode also defines various I<properties> for the characters, like
1N/A"uppercase" or "lowercase", "decimal digit", or "punctuation";
1N/Athese properties are independent of the names of the characters.
1N/AFurthermore, various operations on the characters like uppercasing,
1N/Alowercasing, and collating (sorting) are defined.
1N/A
1N/AA Unicode character consists either of a single code point, or a
1N/AI<base character> (like C<LATIN CAPITAL LETTER A>), followed by one or
1N/Amore I<modifiers> (like C<COMBINING ACUTE ACCENT>). This sequence of
1N/Abase character and modifiers is called a I<combining character
1N/Asequence>.
1N/A
1N/AWhether to call these combining character sequences "characters"
1N/Adepends on your point of view. If you are a programmer, you probably
1N/Awould tend towards seeing each element in the sequences as one unit,
1N/Aor "character". The whole sequence could be seen as one "character",
1N/Ahowever, from the user's point of view, since that's probably what it
1N/Alooks like in the context of the user's language.
1N/A
1N/AWith this "whole sequence" view of characters, the total number of
1N/Acharacters is open-ended. But in the programmer's "one unit is one
1N/Acharacter" point of view, the concept of "characters" is more
1N/Adeterministic. In this document, we take that second point of view:
1N/Aone "character" is one Unicode code point, be it a base character or
1N/Aa combining character.
1N/A
1N/AFor some combinations, there are I<precomposed> characters.
1N/AC<LATIN CAPITAL LETTER A WITH ACUTE>, for example, is defined as
1N/Aa single code point. These precomposed characters are, however,
1N/Aonly available for some combinations, and are mainly
1N/Ameant to support round-trip conversions between Unicode and legacy
1N/Astandards (like the ISO 8859). In the general case, the composing
1N/Amethod is more extensible. To support conversion between
1N/Adifferent compositions of the characters, various I<normalization
1N/Aforms> to standardize representations are also defined.
1N/A
1N/ABecause of backward compatibility with legacy encodings, the "a unique
1N/Anumber for every character" idea breaks down a bit: instead, there is
1N/A"at least one number for every character". The same character could
1N/Abe represented differently in several legacy encodings. The
1N/Aconverse is also not true: some code points do not have an assigned
1N/Acharacter. Firstly, there are unallocated code points within
1N/Aotherwise used blocks. Secondly, there are special Unicode control
1N/Acharacters that do not represent true characters.
1N/A
1N/AA common myth about Unicode is that it would be "16-bit", that is,
1N/AUnicode is only represented as C<0x10000> (or 65536) characters from
1N/AC<0x0000> to C<0xFFFF>. B<This is untrue.> Since Unicode 2.0 (July
1N/A1996), Unicode has been defined all the way up to 21 bits (C<0x10FFFF>),
1N/Aand since Unicode 3.1 (March 2001), characters have been defined
1N/Abeyond C<0xFFFF>. The first C<0x10000> characters are called the
1N/AI<Plane 0>, or the I<Basic Multilingual Plane> (BMP). With Unicode
1N/A3.1, 17 (yes, seventeen) planes in all were defined--but they are
1N/Anowhere near full of defined characters, yet.
1N/A
1N/AAnother myth is that the 256-character blocks have something to
1N/Ado with languages--that each block would define the characters used
1N/Aby a language or a set of languages. B<This is also untrue.>
1N/AThe division into blocks exists, but it is almost completely
1N/Aaccidental--an artifact of how the characters have been and
1N/Astill are allocated. Instead, there is a concept called I<scripts>,
1N/Awhich is more useful: there is C<Latin> script, C<Greek> script, and
1N/Aso on. Scripts usually span varied parts of several blocks.
1N/AFor further information see L<Unicode::UCD>.
1N/A
1N/AThe Unicode code points are just abstract numbers. To input and
1N/Aoutput these abstract numbers, the numbers must be I<encoded> or
1N/AI<serialised> somehow. Unicode defines several I<character encoding
1N/Aforms>, of which I<UTF-8> is perhaps the most popular. UTF-8 is a
1N/Avariable length encoding that encodes Unicode characters as 1 to 6
1N/Abytes (only 4 with the currently defined characters). Other encodings
1N/Ainclude UTF-16 and UTF-32 and their big- and little-endian variants
1N/A(UTF-8 is byte-order independent) The ISO/IEC 10646 defines the UCS-2
1N/Aand UCS-4 encoding forms.
1N/A
1N/AFor more information about encodings--for instance, to learn what
1N/AI<surrogates> and I<byte order marks> (BOMs) are--see L<perlunicode>.
1N/A
1N/A=head2 Perl's Unicode Support
1N/A
1N/AStarting from Perl 5.6.0, Perl has had the capacity to handle Unicode
1N/Anatively. Perl 5.8.0, however, is the first recommended release for
1N/Aserious Unicode work. The maintenance release 5.6.1 fixed many of the
1N/Aproblems of the initial Unicode implementation, but for example
1N/Aregular expressions still do not work with Unicode in 5.6.1.
1N/A
1N/AB<Starting from Perl 5.8.0, the use of C<use utf8> is no longer
1N/Anecessary.> In earlier releases the C<utf8> pragma was used to declare
1N/Athat operations in the current block or file would be Unicode-aware.
1N/AThis model was found to be wrong, or at least clumsy: the "Unicodeness"
1N/Ais now carried with the data, instead of being attached to the
1N/Aoperations. Only one case remains where an explicit C<use utf8> is
1N/Aneeded: if your Perl script itself is encoded in UTF-8, you can use
1N/AUTF-8 in your identifier names, and in string and regular expression
1N/Aliterals, by saying C<use utf8>. This is not the default because
1N/Ascripts with legacy 8-bit data in them would break. See L<utf8>.
1N/A
1N/A=head2 Perl's Unicode Model
1N/A
1N/APerl supports both pre-5.6 strings of eight-bit native bytes, and
1N/Astrings of Unicode characters. The principle is that Perl tries to
1N/Akeep its data as eight-bit bytes for as long as possible, but as soon
1N/Aas Unicodeness cannot be avoided, the data is transparently upgraded
1N/Ato Unicode.
1N/A
1N/AInternally, Perl currently uses either whatever the native eight-bit
1N/Acharacter set of the platform (for example Latin-1) is, defaulting to
1N/AUTF-8, to encode Unicode strings. Specifically, if all code points in
1N/Athe string are C<0xFF> or less, Perl uses the native eight-bit
1N/Acharacter set. Otherwise, it uses UTF-8.
1N/A
1N/AA user of Perl does not normally need to know nor care how Perl
1N/Ahappens to encode its internal strings, but it becomes relevant when
1N/Aoutputting Unicode strings to a stream without a PerlIO layer -- one with
1N/Athe "default" encoding. In such a case, the raw bytes used internally
1N/A(the native character set or UTF-8, as appropriate for each string)
1N/Awill be used, and a "Wide character" warning will be issued if those
1N/Astrings contain a character beyond 0x00FF.
1N/A
1N/AFor example,
1N/A
1N/A perl -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"'
1N/A
1N/Aproduces a fairly useless mixture of native bytes and UTF-8, as well
1N/Aas a warning:
1N/A
1N/A Wide character in print at ...
1N/A
1N/ATo output UTF-8, use the C<:utf8> output layer. Prepending
1N/A
1N/A binmode(STDOUT, ":utf8");
1N/A
1N/Ato this sample program ensures that the output is completely UTF-8,
1N/Aand removes the program's warning.
1N/A
1N/AYou can enable automatic UTF-8-ification of your standard file
1N/Ahandles, default C<open()> layer, and C<@ARGV> by using either
1N/Athe C<-C> command line switch or the C<PERL_UNICODE> environment
1N/Avariable, see L<perlrun> for the documentation of the C<-C> switch.
1N/A
1N/ANote that this means that Perl expects other software to work, too:
1N/Aif Perl has been led to believe that STDIN should be UTF-8, but then
1N/ASTDIN coming in from another command is not UTF-8, Perl will complain
1N/Aabout the malformed UTF-8.
1N/A
1N/AAll features that combine Unicode and I/O also require using the new
1N/APerlIO feature. Almost all Perl 5.8 platforms do use PerlIO, though:
1N/Ayou can see whether yours is by running "perl -V" and looking for
1N/AC<useperlio=define>.
1N/A
1N/A=head2 Unicode and EBCDIC
1N/A
1N/APerl 5.8.0 also supports Unicode on EBCDIC platforms. There,
1N/AUnicode support is somewhat more complex to implement since
1N/Aadditional conversions are needed at every step. Some problems
1N/Aremain, see L<perlebcdic> for details.
1N/A
1N/AIn any case, the Unicode support on EBCDIC platforms is better than
1N/Ain the 5.6 series, which didn't work much at all for EBCDIC platform.
1N/AOn EBCDIC platforms, the internal Unicode encoding form is UTF-EBCDIC
1N/Ainstead of UTF-8. The difference is that as UTF-8 is "ASCII-safe" in
1N/Athat ASCII characters encode to UTF-8 as-is, while UTF-EBCDIC is
1N/A"EBCDIC-safe".
1N/A
1N/A=head2 Creating Unicode
1N/A
1N/ATo create Unicode characters in literals for code points above C<0xFF>,
1N/Ause the C<\x{...}> notation in double-quoted strings:
1N/A
1N/A my $smiley = "\x{263a}";
1N/A
1N/ASimilarly, it can be used in regular expression literals
1N/A
1N/A $smiley =~ /\x{263a}/;
1N/A
1N/AAt run-time you can use C<chr()>:
1N/A
1N/A my $hebrew_alef = chr(0x05d0);
1N/A
1N/ASee L</"Further Resources"> for how to find all these numeric codes.
1N/A
1N/ANaturally, C<ord()> will do the reverse: it turns a character into
1N/Aa code point.
1N/A
1N/ANote that C<\x..> (no C<{}> and only two hexadecimal digits), C<\x{...}>,
1N/Aand C<chr(...)> for arguments less than C<0x100> (decimal 256)
1N/Agenerate an eight-bit character for backward compatibility with older
1N/APerls. For arguments of C<0x100> or more, Unicode characters are
1N/Aalways produced. If you want to force the production of Unicode
1N/Acharacters regardless of the numeric value, use C<pack("U", ...)>
1N/Ainstead of C<\x..>, C<\x{...}>, or C<chr()>.
1N/A
1N/AYou can also use the C<charnames> pragma to invoke characters
1N/Aby name in double-quoted strings:
1N/A
1N/A use charnames ':full';
1N/A my $arabic_alef = "\N{ARABIC LETTER ALEF}";
1N/A
1N/AAnd, as mentioned above, you can also C<pack()> numbers into Unicode
1N/Acharacters:
1N/A
1N/A my $georgian_an = pack("U", 0x10a0);
1N/A
1N/ANote that both C<\x{...}> and C<\N{...}> are compile-time string
1N/Aconstants: you cannot use variables in them. if you want similar
1N/Arun-time functionality, use C<chr()> and C<charnames::vianame()>.
1N/A
1N/AIf you want to force the result to Unicode characters, use the special
1N/AC<"U0"> prefix. It consumes no arguments but forces the result to be
1N/Ain Unicode characters, instead of bytes.
1N/A
1N/A my $chars = pack("U0C*", 0x80, 0x42);
1N/A
1N/ALikewise, you can force the result to be bytes by using the special
1N/AC<"C0"> prefix.
1N/A
1N/A=head2 Handling Unicode
1N/A
1N/AHandling Unicode is for the most part transparent: just use the
1N/Astrings as usual. Functions like C<index()>, C<length()>, and
1N/AC<substr()> will work on the Unicode characters; regular expressions
1N/Awill work on the Unicode characters (see L<perlunicode> and L<perlretut>).
1N/A
1N/ANote that Perl considers combining character sequences to be
1N/Aseparate characters, so for example
1N/A
1N/A use charnames ':full';
1N/A print length("\N{LATIN CAPITAL LETTER A}\N{COMBINING ACUTE ACCENT}"), "\n";
1N/A
1N/Awill print 2, not 1. The only exception is that regular expressions
1N/Ahave C<\X> for matching a combining character sequence.
1N/A
1N/ALife is not quite so transparent, however, when working with legacy
1N/Aencodings, I/O, and certain special cases:
1N/A
1N/A=head2 Legacy Encodings
1N/A
1N/AWhen you combine legacy data and Unicode the legacy data needs
1N/Ato be upgraded to Unicode. Normally ISO 8859-1 (or EBCDIC, if
1N/Aapplicable) is assumed. You can override this assumption by
1N/Ausing the C<encoding> pragma, for example
1N/A
1N/A use encoding 'latin2'; # ISO 8859-2
1N/A
1N/Ain which case literals (string or regular expressions), C<chr()>,
1N/Aand C<ord()> in your whole script are assumed to produce Unicode
1N/Acharacters from ISO 8859-2 code points. Note that the matching for
1N/Aencoding names is forgiving: instead of C<latin2> you could have
1N/Asaid C<Latin 2>, or C<iso8859-2>, or other variations. With just
1N/A
1N/A use encoding;
1N/A
1N/Athe environment variable C<PERL_ENCODING> will be consulted.
1N/AIf that variable isn't set, the encoding pragma will fail.
1N/A
1N/AThe C<Encode> module knows about many encodings and has interfaces
1N/Afor doing conversions between those encodings:
1N/A
1N/A use Encode 'decode';
1N/A $data = decode("iso-8859-3", $data); # convert from legacy to utf-8
1N/A
1N/A=head2 Unicode I/O
1N/A
1N/ANormally, writing out Unicode data
1N/A
1N/A print FH $some_string_with_unicode, "\n";
1N/A
1N/Aproduces raw bytes that Perl happens to use to internally encode the
1N/AUnicode string. Perl's internal encoding depends on the system as
1N/Awell as what characters happen to be in the string at the time. If
1N/Aany of the characters are at code points C<0x100> or above, you will get
1N/Aa warning. To ensure that the output is explicitly rendered in the
1N/Aencoding you desire--and to avoid the warning--open the stream with
1N/Athe desired encoding. Some examples:
1N/A
1N/A open FH, ">:utf8", "file";
1N/A
1N/A open FH, ">:encoding(ucs2)", "file";
1N/A open FH, ">:encoding(UTF-8)", "file";
1N/A open FH, ">:encoding(shift_jis)", "file";
1N/A
1N/Aand on already open streams, use C<binmode()>:
1N/A
1N/A binmode(STDOUT, ":utf8");
1N/A
1N/A binmode(STDOUT, ":encoding(ucs2)");
1N/A binmode(STDOUT, ":encoding(UTF-8)");
1N/A binmode(STDOUT, ":encoding(shift_jis)");
1N/A
1N/AThe matching of encoding names is loose: case does not matter, and
1N/Amany encodings have several aliases. Note that the C<:utf8> layer
1N/Amust always be specified exactly like that; it is I<not> subject to
1N/Athe loose matching of encoding names.
1N/A
1N/ASee L<PerlIO> for the C<:utf8> layer, L<PerlIO::encoding> and
1N/AL<Encode::PerlIO> for the C<:encoding()> layer, and
1N/AL<Encode::Supported> for many encodings supported by the C<Encode>
1N/Amodule.
1N/A
1N/AReading in a file that you know happens to be encoded in one of the
1N/AUnicode or legacy encodings does not magically turn the data into
1N/AUnicode in Perl's eyes. To do that, specify the appropriate
1N/Alayer when opening files
1N/A
1N/A open(my $fh,'<:utf8', 'anything');
1N/A my $line_of_unicode = <$fh>;
1N/A
1N/A open(my $fh,'<:encoding(Big5)', 'anything');
1N/A my $line_of_unicode = <$fh>;
1N/A
1N/AThe I/O layers can also be specified more flexibly with
1N/Athe C<open> pragma. See L<open>, or look at the following example.
1N/A
1N/A use open ':utf8'; # input and output default layer will be UTF-8
1N/A open X, ">file";
1N/A print X chr(0x100), "\n";
1N/A close X;
1N/A open Y, "<file";
1N/A printf "%#x\n", ord(<Y>); # this should print 0x100
1N/A close Y;
1N/A
1N/AWith the C<open> pragma you can use the C<:locale> layer
1N/A
1N/A BEGIN { $ENV{LC_ALL} = $ENV{LANG} = 'ru_RU.KOI8-R' }
1N/A # the :locale will probe the locale environment variables like LC_ALL
1N/A use open OUT => ':locale'; # russki parusski
1N/A open(O, ">koi8");
1N/A print O chr(0x430); # Unicode CYRILLIC SMALL LETTER A = KOI8-R 0xc1
1N/A close O;
1N/A open(I, "<koi8");
1N/A printf "%#x\n", ord(<I>), "\n"; # this should print 0xc1
1N/A close I;
1N/A
1N/Aor you can also use the C<':encoding(...)'> layer
1N/A
1N/A open(my $epic,'<:encoding(iso-8859-7)','iliad.greek');
1N/A my $line_of_unicode = <$epic>;
1N/A
1N/AThese methods install a transparent filter on the I/O stream that
1N/Aconverts data from the specified encoding when it is read in from the
1N/Astream. The result is always Unicode.
1N/A
1N/AThe L<open> pragma affects all the C<open()> calls after the pragma by
1N/Asetting default layers. If you want to affect only certain
1N/Astreams, use explicit layers directly in the C<open()> call.
1N/A
1N/AYou can switch encodings on an already opened stream by using
1N/AC<binmode()>; see L<perlfunc/binmode>.
1N/A
1N/AThe C<:locale> does not currently (as of Perl 5.8.0) work with
1N/AC<open()> and C<binmode()>, only with the C<open> pragma. The
1N/AC<:utf8> and C<:encoding(...)> methods do work with all of C<open()>,
1N/AC<binmode()>, and the C<open> pragma.
1N/A
1N/ASimilarly, you may use these I/O layers on output streams to
1N/Aautomatically convert Unicode to the specified encoding when it is
1N/Awritten to the stream. For example, the following snippet copies the
1N/Acontents of the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to
1N/Athe file "text.utf8", encoded as UTF-8:
1N/A
1N/A open(my $nihongo, '<:encoding(iso-2022-jp)', 'text.jis');
1N/A open(my $unicode, '>:utf8', 'text.utf8');
1N/A while (<$nihongo>) { print $unicode $_ }
1N/A
1N/AThe naming of encodings, both by the C<open()> and by the C<open>
1N/Apragma, is similar to the C<encoding> pragma in that it allows for
1N/Aflexible names: C<koi8-r> and C<KOI8R> will both be understood.
1N/A
1N/ACommon encodings recognized by ISO, MIME, IANA, and various other
1N/Astandardisation organisations are recognised; for a more detailed
1N/Alist see L<Encode::Supported>.
1N/A
1N/AC<read()> reads characters and returns the number of characters.
1N/AC<seek()> and C<tell()> operate on byte counts, as do C<sysread()>
1N/Aand C<sysseek()>.
1N/A
1N/ANotice that because of the default behaviour of not doing any
1N/Aconversion upon input if there is no default layer,
1N/Ait is easy to mistakenly write code that keeps on expanding a file
1N/Aby repeatedly encoding the data:
1N/A
1N/A # BAD CODE WARNING
1N/A open F, "file";
1N/A local $/; ## read in the whole file of 8-bit characters
1N/A $t = <F>;
1N/A close F;
1N/A open F, ">:utf8", "file";
1N/A print F $t; ## convert to UTF-8 on output
1N/A close F;
1N/A
1N/AIf you run this code twice, the contents of the F<file> will be twice
1N/AUTF-8 encoded. A C<use open ':utf8'> would have avoided the bug, or
1N/Aexplicitly opening also the F<file> for input as UTF-8.
1N/A
1N/AB<NOTE>: the C<:utf8> and C<:encoding> features work only if your
1N/APerl has been built with the new PerlIO feature (which is the default
1N/Aon most systems).
1N/A
1N/A=head2 Displaying Unicode As Text
1N/A
1N/ASometimes you might want to display Perl scalars containing Unicode as
1N/Asimple ASCII (or EBCDIC) text. The following subroutine converts
1N/Aits argument so that Unicode characters with code points greater than
1N/A255 are displayed as C<\x{...}>, control characters (like C<\n>) are
1N/Adisplayed as C<\x..>, and the rest of the characters as themselves:
1N/A
1N/A sub nice_string {
1N/A join("",
1N/A map { $_ > 255 ? # if wide character...
1N/A sprintf("\\x{%04X}", $_) : # \x{...}
1N/A chr($_) =~ /[[:cntrl:]]/ ? # else if control character ...
1N/A sprintf("\\x%02X", $_) : # \x..
1N/A quotemeta(chr($_)) # else quoted or as themselves
1N/A } unpack("U*", $_[0])); # unpack Unicode characters
1N/A }
1N/A
1N/AFor example,
1N/A
1N/A nice_string("foo\x{100}bar\n")
1N/A
1N/Areturns the string
1N/A
1N/A 'foo\x{0100}bar\x0A'
1N/A
1N/Awhich is ready to be printed.
1N/A
1N/A=head2 Special Cases
1N/A
1N/A=over 4
1N/A
1N/A=item *
1N/A
1N/ABit Complement Operator ~ And vec()
1N/A
1N/AThe bit complement operator C<~> may produce surprising results if
1N/Aused on strings containing characters with ordinal values above
1N/A255. In such a case, the results are consistent with the internal
1N/Aencoding of the characters, but not with much else. So don't do
1N/Athat. Similarly for C<vec()>: you will be operating on the
1N/Ainternally-encoded bit patterns of the Unicode characters, not on
1N/Athe code point values, which is very probably not what you want.
1N/A
1N/A=item *
1N/A
1N/APeeking At Perl's Internal Encoding
1N/A
1N/ANormal users of Perl should never care how Perl encodes any particular
1N/AUnicode string (because the normal ways to get at the contents of a
1N/Astring with Unicode--via input and output--should always be via
1N/Aexplicitly-defined I/O layers). But if you must, there are two
1N/Aways of looking behind the scenes.
1N/A
1N/AOne way of peeking inside the internal encoding of Unicode characters
1N/Ais to use C<unpack("C*", ...> to get the bytes or C<unpack("H*", ...)>
1N/Ato display the bytes:
1N/A
1N/A # this prints c4 80 for the UTF-8 bytes 0xc4 0x80
1N/A print join(" ", unpack("H*", pack("U", 0x100))), "\n";
1N/A
1N/AYet another way would be to use the Devel::Peek module:
1N/A
1N/A perl -MDevel::Peek -e 'Dump(chr(0x100))'
1N/A
1N/AThat shows the C<UTF8> flag in FLAGS and both the UTF-8 bytes
1N/Aand Unicode characters in C<PV>. See also later in this document
1N/Athe discussion about the C<utf8::is_utf8()> function.
1N/A
1N/A=back
1N/A
1N/A=head2 Advanced Topics
1N/A
1N/A=over 4
1N/A
1N/A=item *
1N/A
1N/AString Equivalence
1N/A
1N/AThe question of string equivalence turns somewhat complicated
1N/Ain Unicode: what do you mean by "equal"?
1N/A
1N/A(Is C<LATIN CAPITAL LETTER A WITH ACUTE> equal to
1N/AC<LATIN CAPITAL LETTER A>?)
1N/A
1N/AThe short answer is that by default Perl compares equivalence (C<eq>,
1N/AC<ne>) based only on code points of the characters. In the above
1N/Acase, the answer is no (because 0x00C1 != 0x0041). But sometimes, any
1N/ACAPITAL LETTER As should be considered equal, or even As of any case.
1N/A
1N/AThe long answer is that you need to consider character normalization
1N/Aand casing issues: see L<Unicode::Normalize>, Unicode Technical
1N/AReports #15 and #21, I<Unicode Normalization Forms> and I<Case
1N/AMappings>, http://www.unicode.org/unicode/reports/tr15/ and
1N/Ahttp://www.unicode.org/unicode/reports/tr21/
1N/A
1N/AAs of Perl 5.8.0, the "Full" case-folding of I<Case
1N/AMappings/SpecialCasing> is implemented.
1N/A
1N/A=item *
1N/A
1N/AString Collation
1N/A
1N/APeople like to see their strings nicely sorted--or as Unicode
1N/Aparlance goes, collated. But again, what do you mean by collate?
1N/A
1N/A(Does C<LATIN CAPITAL LETTER A WITH ACUTE> come before or after
1N/AC<LATIN CAPITAL LETTER A WITH GRAVE>?)
1N/A
1N/AThe short answer is that by default, Perl compares strings (C<lt>,
1N/AC<le>, C<cmp>, C<ge>, C<gt>) based only on the code points of the
1N/Acharacters. In the above case, the answer is "after", since
1N/AC<0x00C1> > C<0x00C0>.
1N/A
1N/AThe long answer is that "it depends", and a good answer cannot be
1N/Agiven without knowing (at the very least) the language context.
1N/ASee L<Unicode::Collate>, and I<Unicode Collation Algorithm>
1N/Ahttp://www.unicode.org/unicode/reports/tr10/
1N/A
1N/A=back
1N/A
1N/A=head2 Miscellaneous
1N/A
1N/A=over 4
1N/A
1N/A=item *
1N/A
1N/ACharacter Ranges and Classes
1N/A
1N/ACharacter ranges in regular expression character classes (C</[a-z]/>)
1N/Aand in the C<tr///> (also known as C<y///>) operator are not magically
1N/AUnicode-aware. What this means that C<[A-Za-z]> will not magically start
1N/Ato mean "all alphabetic letters"; not that it does mean that even for
1N/A8-bit characters, you should be using C</[[:alpha:]]/> in that case.
1N/A
1N/AFor specifying character classes like that in regular expressions,
1N/Ayou can use the various Unicode properties--C<\pL>, or perhaps
1N/AC<\p{Alphabetic}>, in this particular case. You can use Unicode
1N/Acode points as the end points of character ranges, but there is no
1N/Amagic associated with specifying a certain range. For further
1N/Ainformation--there are dozens of Unicode character classes--see
1N/AL<perlunicode>.
1N/A
1N/A=item *
1N/A
1N/AString-To-Number Conversions
1N/A
1N/AUnicode does define several other decimal--and numeric--characters
1N/Abesides the familiar 0 to 9, such as the Arabic and Indic digits.
1N/APerl does not support string-to-number conversion for digits other
1N/Athan ASCII 0 to 9 (and ASCII a to f for hexadecimal).
1N/A
1N/A=back
1N/A
1N/A=head2 Questions With Answers
1N/A
1N/A=over 4
1N/A
1N/A=item *
1N/A
1N/AWill My Old Scripts Break?
1N/A
1N/AVery probably not. Unless you are generating Unicode characters
1N/Asomehow, old behaviour should be preserved. About the only behaviour
1N/Athat has changed and which could start generating Unicode is the old
1N/Abehaviour of C<chr()> where supplying an argument more than 255
1N/Aproduced a character modulo 255. C<chr(300)>, for example, was equal
1N/Ato C<chr(45)> or "-" (in ASCII), now it is LATIN CAPITAL LETTER I WITH
1N/ABREVE.
1N/A
1N/A=item *
1N/A
1N/AHow Do I Make My Scripts Work With Unicode?
1N/A
1N/AVery little work should be needed since nothing changes until you
1N/Agenerate Unicode data. The most important thing is getting input as
1N/AUnicode; for that, see the earlier I/O discussion.
1N/A
1N/A=item *
1N/A
1N/AHow Do I Know Whether My String Is In Unicode?
1N/A
1N/AYou shouldn't care. No, you really shouldn't. No, really. If you
1N/Ahave to care--beyond the cases described above--it means that we
1N/Adidn't get the transparency of Unicode quite right.
1N/A
1N/AOkay, if you insist:
1N/A
1N/A print utf8::is_utf8($string) ? 1 : 0, "\n";
1N/A
1N/ABut note that this doesn't mean that any of the characters in the
1N/Astring are necessary UTF-8 encoded, or that any of the characters have
1N/Acode points greater than 0xFF (255) or even 0x80 (128), or that the
1N/Astring has any characters at all. All the C<is_utf8()> does is to
1N/Areturn the value of the internal "utf8ness" flag attached to the
1N/AC<$string>. If the flag is off, the bytes in the scalar are interpreted
1N/Aas a single byte encoding. If the flag is on, the bytes in the scalar
1N/Aare interpreted as the (multi-byte, variable-length) UTF-8 encoded code
1N/Apoints of the characters. Bytes added to an UTF-8 encoded string are
1N/Aautomatically upgraded to UTF-8. If mixed non-UTF-8 and UTF-8 scalars
1N/Aare merged (double-quoted interpolation, explicit concatenation, and
1N/Aprintf/sprintf parameter substitution), the result will be UTF-8 encoded
1N/Aas if copies of the byte strings were upgraded to UTF-8: for example,
1N/A
1N/A $a = "ab\x80c";
1N/A $b = "\x{100}";
1N/A print "$a = $b\n";
1N/A
1N/Athe output string will be UTF-8-encoded C<ab\x80c = \x{100}\n>, but
1N/AC<$a> will stay byte-encoded.
1N/A
1N/ASometimes you might really need to know the byte length of a string
1N/Ainstead of the character length. For that use either the
1N/AC<Encode::encode_utf8()> function or the C<bytes> pragma and its only
1N/Adefined function C<length()>:
1N/A
1N/A my $unicode = chr(0x100);
1N/A print length($unicode), "\n"; # will print 1
1N/A require Encode;
1N/A print length(Encode::encode_utf8($unicode)), "\n"; # will print 2
1N/A use bytes;
1N/A print length($unicode), "\n"; # will also print 2
1N/A # (the 0xC4 0x80 of the UTF-8)
1N/A
1N/A=item *
1N/A
1N/AHow Do I Detect Data That's Not Valid In a Particular Encoding?
1N/A
1N/AUse the C<Encode> package to try converting it.
1N/AFor example,
1N/A
1N/A use Encode 'encode_utf8';
1N/A if (encode_utf8($string_of_bytes_that_I_think_is_utf8)) {
1N/A # valid
1N/A } else {
1N/A # invalid
1N/A }
1N/A
1N/AFor UTF-8 only, you can use:
1N/A
1N/A use warnings;
1N/A @chars = unpack("U0U*", $string_of_bytes_that_I_think_is_utf8);
1N/A
1N/AIf invalid, a C<Malformed UTF-8 character (byte 0x##) in unpack>
1N/Awarning is produced. The "U0" means "expect strictly UTF-8 encoded
1N/AUnicode". Without that the C<unpack("U*", ...)> would accept also
1N/Adata like C<chr(0xFF>), similarly to the C<pack> as we saw earlier.
1N/A
1N/A=item *
1N/A
1N/AHow Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa?
1N/A
1N/AThis probably isn't as useful as you might think.
1N/ANormally, you shouldn't need to.
1N/A
1N/AIn one sense, what you are asking doesn't make much sense: encodings
1N/Aare for characters, and binary data are not "characters", so converting
1N/A"data" into some encoding isn't meaningful unless you know in what
1N/Acharacter set and encoding the binary data is in, in which case it's
1N/Anot just binary data, now is it?
1N/A
1N/AIf you have a raw sequence of bytes that you know should be
1N/Ainterpreted via a particular encoding, you can use C<Encode>:
1N/A
1N/A use Encode 'from_to';
1N/A from_to($data, "iso-8859-1", "utf-8"); # from latin-1 to utf-8
1N/A
1N/AThe call to C<from_to()> changes the bytes in C<$data>, but nothing
1N/Amaterial about the nature of the string has changed as far as Perl is
1N/Aconcerned. Both before and after the call, the string C<$data>
1N/Acontains just a bunch of 8-bit bytes. As far as Perl is concerned,
1N/Athe encoding of the string remains as "system-native 8-bit bytes".
1N/A
1N/AYou might relate this to a fictional 'Translate' module:
1N/A
1N/A use Translate;
1N/A my $phrase = "Yes";
1N/A Translate::from_to($phrase, 'english', 'deutsch');
1N/A ## phrase now contains "Ja"
1N/A
1N/AThe contents of the string changes, but not the nature of the string.
1N/APerl doesn't know any more after the call than before that the
1N/Acontents of the string indicates the affirmative.
1N/A
1N/ABack to converting data. If you have (or want) data in your system's
1N/Anative 8-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use
1N/Apack/unpack to convert to/from Unicode.
1N/A
1N/A $native_string = pack("C*", unpack("U*", $Unicode_string));
1N/A $Unicode_string = pack("U*", unpack("C*", $native_string));
1N/A
1N/AIf you have a sequence of bytes you B<know> is valid UTF-8,
1N/Abut Perl doesn't know it yet, you can make Perl a believer, too:
1N/A
1N/A use Encode 'decode_utf8';
1N/A $Unicode = decode_utf8($bytes);
1N/A
1N/AYou can convert well-formed UTF-8 to a sequence of bytes, but if
1N/Ayou just want to convert random binary data into UTF-8, you can't.
1N/AB<Any random collection of bytes isn't well-formed UTF-8>. You can
1N/Ause C<unpack("C*", $string)> for the former, and you can create
1N/Awell-formed Unicode data by C<pack("U*", 0xff, ...)>.
1N/A
1N/A=item *
1N/A
1N/AHow Do I Display Unicode? How Do I Input Unicode?
1N/A
1N/ASee http://www.alanwood.net/unicode/ and
1N/Ahttp://www.cl.cam.ac.uk/~mgk25/unicode.html
1N/A
1N/A=item *
1N/A
1N/AHow Does Unicode Work With Traditional Locales?
1N/A
1N/AIn Perl, not very well. Avoid using locales through the C<locale>
1N/Apragma. Use only one or the other. But see L<perlrun> for the
1N/Adescription of the C<-C> switch and its environment counterpart,
1N/AC<$ENV{PERL_UNICODE}> to see how to enable various Unicode features,
1N/Afor example by using locale settings.
1N/A
1N/A=back
1N/A
1N/A=head2 Hexadecimal Notation
1N/A
1N/AThe Unicode standard prefers using hexadecimal notation because
1N/Athat more clearly shows the division of Unicode into blocks of 256 characters.
1N/AHexadecimal is also simply shorter than decimal. You can use decimal
1N/Anotation, too, but learning to use hexadecimal just makes life easier
1N/Awith the Unicode standard. The C<U+HHHH> notation uses hexadecimal,
1N/Afor example.
1N/A
1N/AThe C<0x> prefix means a hexadecimal number, the digits are 0-9 I<and>
1N/Aa-f (or A-F, case doesn't matter). Each hexadecimal digit represents
1N/Afour bits, or half a byte. C<print 0x..., "\n"> will show a
1N/Ahexadecimal number in decimal, and C<printf "%x\n", $decimal> will
1N/Ashow a decimal number in hexadecimal. If you have just the
1N/A"hex digits" of a hexadecimal number, you can use the C<hex()> function.
1N/A
1N/A print 0x0009, "\n"; # 9
1N/A print 0x000a, "\n"; # 10
1N/A print 0x000f, "\n"; # 15
1N/A print 0x0010, "\n"; # 16
1N/A print 0x0011, "\n"; # 17
1N/A print 0x0100, "\n"; # 256
1N/A
1N/A print 0x0041, "\n"; # 65
1N/A
1N/A printf "%x\n", 65; # 41
1N/A printf "%#x\n", 65; # 0x41
1N/A
1N/A print hex("41"), "\n"; # 65
1N/A
1N/A=head2 Further Resources
1N/A
1N/A=over 4
1N/A
1N/A=item *
1N/A
1N/AUnicode Consortium
1N/A
1N/A http://www.unicode.org/
1N/A
1N/A=item *
1N/A
1N/AUnicode FAQ
1N/A
1N/A http://www.unicode.org/unicode/faq/
1N/A
1N/A=item *
1N/A
1N/AUnicode Glossary
1N/A
1N/A http://www.unicode.org/glossary/
1N/A
1N/A=item *
1N/A
1N/AUnicode Useful Resources
1N/A
1N/A http://www.unicode.org/unicode/onlinedat/resources.html
1N/A
1N/A=item *
1N/A
1N/AUnicode and Multilingual Support in HTML, Fonts, Web Browsers and Other Applications
1N/A
1N/A http://www.alanwood.net/unicode/
1N/A
1N/A=item *
1N/A
1N/AUTF-8 and Unicode FAQ for Unix/Linux
1N/A
1N/A http://www.cl.cam.ac.uk/~mgk25/unicode.html
1N/A
1N/A=item *
1N/A
1N/ALegacy Character Sets
1N/A
1N/A http://www.czyborra.com/
1N/A http://www.eki.ee/letter/
1N/A
1N/A=item *
1N/A
1N/AThe Unicode support files live within the Perl installation in the
1N/Adirectory
1N/A
1N/A $Config{installprivlib}/unicore
1N/A
1N/Ain Perl 5.8.0 or newer, and
1N/A
1N/A $Config{installprivlib}/unicode
1N/A
1N/Ain the Perl 5.6 series. (The renaming to F<lib/unicore> was done to
1N/Aavoid naming conflicts with lib/Unicode in case-insensitive filesystems.)
1N/AThe main Unicode data file is F<UnicodeData.txt> (or F<Unicode.301> in
1N/APerl 5.6.1.) You can find the C<$Config{installprivlib}> by
1N/A
1N/A perl "-V:installprivlib"
1N/A
1N/AYou can explore various information from the Unicode data files using
1N/Athe C<Unicode::UCD> module.
1N/A
1N/A=back
1N/A
1N/A=head1 UNICODE IN OLDER PERLS
1N/A
1N/AIf you cannot upgrade your Perl to 5.8.0 or later, you can still
1N/Ado some Unicode processing by using the modules C<Unicode::String>,
1N/AC<Unicode::Map8>, and C<Unicode::Map>, available from CPAN.
1N/AIf you have the GNU recode installed, you can also use the
1N/APerl front-end C<Convert::Recode> for character conversions.
1N/A
1N/AThe following are fast conversions from ISO 8859-1 (Latin-1) bytes
1N/Ato UTF-8 bytes and back, the code works even with older Perl 5 versions.
1N/A
1N/A # ISO 8859-1 to UTF-8
1N/A s/([\x80-\xFF])/chr(0xC0|ord($1)>>6).chr(0x80|ord($1)&0x3F)/eg;
1N/A
1N/A # UTF-8 to ISO 8859-1
1N/A s/([\xC2\xC3])([\x80-\xBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg;
1N/A
1N/A=head1 SEE ALSO
1N/A
1N/AL<perlunicode>, L<Encode>, L<encoding>, L<open>, L<utf8>, L<bytes>,
1N/AL<perlretut>, L<perlrun>, L<Unicode::Collate>, L<Unicode::Normalize>,
1N/AL<Unicode::UCD>
1N/A
1N/A=head1 ACKNOWLEDGMENTS
1N/A
1N/AThanks to the kind readers of the perl5-porters@perl.org,
1N/Aperl-unicode@perl.org, linux-utf8@nl.linux.org, and unicore@unicode.org
1N/Amailing lists for their valuable feedback.
1N/A
1N/A=head1 AUTHOR, COPYRIGHT, AND LICENSE
1N/A
1N/ACopyright 2001-2002 Jarkko Hietaniemi E<lt>jhi@iki.fiE<gt>
1N/A
1N/AThis document may be distributed under the same terms as Perl itself.