4 Encode - character encodings
12 The C<Encode> module provides the interfaces between Perl's strings
13 and the rest of the system. Perl strings are sequences of B<characters>.
15 The repertoire of characters that Perl can represent is at least that
16 defined by the Unicode Consortium. On most platforms the ordinal
17 values of the characters (as returned by C<ord(ch)>) is the "Unicode
18 codepoint" for the character (the exceptions are those platforms where
19 the legacy encoding is some variant of EBCDIC rather than a super-set
20 of ASCII - see L<perlebcdic>).
22 Traditionaly computer data has been moved around in 8-bit chunks
23 often called "bytes". These chunks are also known as "octets" in
24 networking standards. Perl is widely used to manipulate data of
25 many types - not only strings of characters representing human or
26 computer languages but also "binary" data being the machines representation
27 of numbers, pixels in an image - or just about anything.
29 When Perl is processing "binary data" the programmer wants Perl to process
30 "sequences of bytes". This is not a problem for Perl - as a byte has 256
31 possible values it easily fits in Perl's much larger "logical character".
33 Due to size concerns, each of B<CJK> (Chinese, Japanese & Korean) modules
34 are not loaded in memory until the first time they're used. Although you
35 don't have to C<use> the corresponding B<Encode::>(B<TW>|B<CN>|B<JP>|B<KR>)
36 modules first, be aware that those encodings will not be in C<%encodings>
37 until their module is loaded (either implicitly through using encodings
38 contained in the same module, or via an explicit C<use>).
46 I<character>: a character in the range 0..(2**32-1) (or more).
47 (What Perl's strings are made of.)
51 I<byte>: a character in the range 0..255
52 (A special case of a Perl character.)
56 I<octet>: 8 bits of data, with ordinal values 0..255
57 (Term for bytes passed to or from a non-Perl context, e.g. disk file.)
61 The marker [INTERNAL] marks Internal Implementation Details, in
62 general meant only for those who think they know what they are doing,
63 and such details may change in future releases.
67 =head2 Characteristics of an Encoding
69 An encoding has a "repertoire" of characters that it can represent,
70 and for each representable character there is at least one sequence of
71 octets that represents it.
73 =head2 Types of Encodings
75 Encodings can be divided into the following types:
79 =item * Fixed length 8-bit (or less) encodings.
81 Each character is a single octet so may have a repertoire of up to
82 256 characters. ASCII and iso-8859-* are typical examples.
84 =item * Fixed length 16-bit encodings
86 Each character is two octets so may have a repertoire of up to
87 65 536 characters. Unicode's UCS-2 is an example. Also used for
88 encodings for East Asian languages.
90 =item * Fixed length 32-bit encodings.
92 Not really very "encoded" encodings. The Unicode code points
93 are just represented as 4-octet integers. None the less because
94 different architectures use different representations of integers
95 (so called "endian") there at least two disctinct encodings.
97 =item * Multi-byte encodings
99 The number of octets needed to represent a character varies.
100 UTF-8 is a particularly complex but regular case of a multi-byte
101 encoding. Several East Asian countries use a multi-byte encoding
102 where 1-octet is used to cover western roman characters and Asian
103 characters get 2-octets.
104 (UTF-16 is strictly a multi-byte encoding taking either 2 or 4 octets
105 to represent a Unicode code point.)
107 =item * "Escape" encodings.
109 These encodings embed "escape sequences" into the octet sequence
110 which describe how the following octets are to be interpreted.
111 The iso-2022-* family is typical. Following the escape sequence
112 octets are encoded by an "embedded" encoding (which will be one
113 of the above types) until another escape sequence switches to
114 a different "embedded" encoding.
116 These schemes are very flexible and can handle mixed languages but are
117 very complex to process (and have state). No escape encodings are
118 implemented for Perl yet.
122 =head2 Specifying Encodings
124 Encodings can be specified to the API described below in two ways:
130 Encoding names are strings with characters taken from a restricted
131 repertoire. See L</"Encoding Names">.
133 =item 2. As an object
135 Encoding objects are returned by C<find_encoding($name, [$skip_external])>.
136 If the second parameter is true, Encode will refrain from loading external
137 modules for CJK encodings.
141 =head2 Encoding Names
143 Encoding names are case insensitive. White space in names is ignored.
144 In addition an encoding may have aliases. Each encoding has one
145 "canonical" name. The "canonical" name is chosen from the names of
146 the encoding by picking the first in the following sequence:
150 =item * The MIME name as defined in IETF RFCs.
152 =item * The name in the IANA registry.
154 =item * The name used by the organization that defined it.
158 Because of all the alias issues, and because in the general case
159 encodings have state C<Encode> uses the encoding object internally
160 once an operation is in progress.
162 As of Perl 5.8.0, at least the following encodings are recognized
163 (the => marks aliases):
177 The ISO 8859 and KOI:
179 ISO 8859-1 ISO 8859-6 ISO 8859-11 KOI8-F
180 ISO 8859-2 ISO 8859-7 (12 doesn't exist) KOI8-R
181 ISO 8859-3 ISO 8859-8 ISO 8859-13 KOI8-U
182 ISO 8859-4 ISO 8859-9 ISO 8859-14
183 ISO 8859-5 ISO 8859-10 ISO 8859-15
186 Latin1 => 8859-1 Latin6 => 8859-10
187 Latin2 => 8859-2 Latin7 => 8859-13
188 Latin3 => 8859-3 Latin8 => 8859-14
189 Latin4 => 8859-4 Latin9 => 8859-15
190 Latin5 => 8859-9 Latin10 => 8859-16
199 The CJKV: Chinese, Japanese, Korean, Vietnamese:
201 ISO 2022 ISO 2022 JP-1 JIS 0201 GB 1988 Big5 EUC-CN
202 ISO 2022 CN ISO 2022 JP-2 JIS 0208 GB 2312 HZ EUC-JP
203 ISO 2022 JP ISO 2022 KR JIS 0210 GB 12345 CNS 11643 EUC-JP-0212
204 Shift-JIS GBK Big5-HKSCS EUC-KR
207 (Due to size concerns, additional Chinese encodings including C<GB 18030>,
208 C<EUC-TW> and C<BIG5PLUS> are distributed separately on CPAN, under the name
209 L<Encode::HanExtra>.)
213 CP37 CP852 CP861 CP866 CP949 CP1251 CP1256
214 CP424 CP855 CP862 CP869 CP950 CP1252 CP1257
215 CP737 CP856 CP863 CP874 CP1006 CP1253 CP1258
216 CP775 CP857 CP864 CP932 CP1047 CP1254
217 CP850 CP860 CP865 CP936 CP1250 CP1255
221 WinCyrillic => CP1251
223 WinTurkiskh => CP1254
227 WinVietnamese => CP1258
229 (All the CPI<NNN...> are available also as IBMI<NNN...>.)
233 MacCentralEuropean MacJapanese
235 MacCyrillic MacRomanian
238 MacIcelandic MacTurkish
249 =head2 Encoding Classification
253 US-ASCII UTF-8 KOI8-R ISO-8859-*
254 ISO-2022-CN ISO-2022-JP ISO-2022-KR Big5
257 are L<http://www.iana.org/assignments/character-sets>-registered
258 as preferred MIME names and may probably be used over the Internet.
263 but despite its wide spread it bears the label of being
264 Microsft proprietary.
266 UTF-16 KOI8-U ISO-2022-JP-2
268 are IANA-registered preferred MIME names but probably shoule
269 be avoided as encoding for web pages due to lack of browser
273 ISO-2022 (http://www.ecma.ch/ecma1/STAND/ECMA-035.HTM)
274 ISO-2022-JP-1 (http://www.faqs.org/rfcs/rfc2237.html)
275 ISO-IR-165 (http://www.faqs.org/rfcs/rfc1345.html)
278 GB 12345 (only plains 1 and 2 available)
282 are totally valid encodings but not registered at IANA.
285 EUC-JP-0212 (Encode::lib::Encode::Tcl::Extended)
287 are a bit proprietary
289 You may probably get some info on CJK encodings at
291 brief description for most of the mentioned CJK encodings
292 http://www.debian.org.ru/doc/manuals/intro-i18n/ch-codes.html
294 several years old, but still useful
295 http://www.oreilly.com/people/authors/lunde/cjk_inf.html
297 and some in-depth reading for the heroes :-)
298 http://www.ecma.ch/ecma1/STAND/ECMA-035.HTM (eq ISO-2022)
299 http://www.faqs.org/rfcs/rfc1345.txt
302 =head1 PERL ENCODING API
304 =head2 Generic Encoding Interface
310 $bytes = encode(ENCODING, $string[, CHECK])
312 Encodes string from Perl's internal form into I<ENCODING> and returns
313 a sequence of octets. For CHECK see L</"Handling Malformed Data">.
315 For example to convert (internally UTF-8 encoded) Unicode data
318 $octets = encode("utf8", $unicode);
322 $string = decode(ENCODING, $bytes[, CHECK])
324 Decode sequence of octets assumed to be in I<ENCODING> into Perl's
325 internal form and returns the resulting string. For CHECK see
326 L</"Handling Malformed Data">.
328 For example to convert ISO-8859-1 data to UTF-8:
330 $utf8 = decode("latin1", $latin1);
334 from_to($string, FROM_ENCODING, TO_ENCODING[, CHECK])
336 Convert B<in-place> the data between two encodings. How did the data
337 in $string originally get to be in FROM_ENCODING? Either using
338 encode() or through PerlIO: See L</"Encoding and IO">. For CHECK
339 see L</"Handling Malformed Data">.
341 For example to convert ISO-8859-1 data to UTF-8:
343 from_to($data, "iso-8859-1", "utf-8");
345 and to convert it back:
347 from_to($data, "utf-8", "iso-8859-1");
349 Note that because the conversion happens in place, the data to be
350 converted cannot be a string constant, it must be a scalar variable.
354 =head2 Handling Malformed Data
356 If CHECK is not set, C<undef> is returned. If the data is supposed to
357 be UTF-8, an optional lexical warning (category utf8) is given. If
358 CHECK is true but not a code reference, dies.
360 It would desirable to have a way to indicate that transform should use
361 the encodings "replacement character" - no such mechanism is defined yet.
363 It is also planned to allow I<CHECK> to be a code reference.
365 This is not yet implemented as there are design issues with what its
366 arguments should be and how it returns its results.
372 Passed remaining fragment of string being processed.
373 Modifies it in place to remove bytes/characters it can understand
374 and returns a string used to represent them.
378 my $ch = substr($_[0],0,1,'');
379 return sprintf("\x{%02X}",ord($ch);
382 This scheme is close to how underlying C code for Encode works, but gives
383 the fixup routine very little context.
387 Passed original string, and an index into it of the problem area, and
388 output string so far. Appends what it will to output string and
389 returns new index into original string. For example:
392 # my ($s,$i,$d) = @_;
393 my $ch = substr($_[0],$_[1],1);
394 $_[2] .= sprintf("\x{%02X}",ord($ch);
398 This scheme gives maximal control to the fixup routine but is more
399 complicated to code, and may need internals of Encode to be tweaked to
400 keep original string intact.
406 Multiple return values rather than in-place modifications.
408 Index into the string could be pos($str) allowing s/\G...//.
414 The Unicode consortium defines the UTF-8 standard as a way of encoding
415 the entire Unicode repertiore as sequences of octets. This encoding is
416 expected to become very widespread. Perl can use this form internaly
417 to represent strings, so conversions to and from this form are
418 particularly efficient (as octets in memory do not have to change,
419 just the meta-data that tells Perl how to treat them).
425 $bytes = encode_utf8($string);
427 The characters that comprise string are encoded in Perl's superset of UTF-8
428 and the resulting octets returned as a sequence of bytes. All possible
429 characters have a UTF-8 representation so this function cannot fail.
433 $string = decode_utf8($bytes [,CHECK]);
435 The sequence of octets represented by $bytes is decoded from UTF-8
436 into a sequence of logical characters. Not all sequences of octets
437 form valid UTF-8 encodings, so it is possible for this call to fail.
438 For CHECK see L</"Handling Malformed Data">.
442 =head2 Other Encodings of Unicode
444 UTF-16 is similar to UCS-2, 16 bit or 2-byte chunks. UCS-2 can only
445 represent 0..0xFFFF, while UTF-16 has a I<surrogate pair> scheme which
446 allows it to cover the whole Unicode range.
448 Surrogates are code points set aside to encode the 0x01000..0x10FFFF
449 range of Unicode code points in pairs of 16-bit units. The I<high
450 surrogates> are the range 0xD800..0xDBFF, and the I<low surrogates>
451 are the range 0xDC00..0xDFFFF. The surrogate encoding is
453 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
454 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
458 $uni = 0x10000 + ($hi - 0xD8000) * 0x400 + ($lo - 0xDC00);
460 Encode implements big-endian UCS-2 aliased to "iso-10646-1" as that
461 happens to be the name used by that representation when used with X11
464 UTF-32 or UCS-4 is 32-bit or 4-byte chunks. Perl's logical characters
465 can be considered as being in this form without encoding. An encoding
466 to transfer strings in this form (e.g. to write them to a file) would
469 pack('L*', unpack('U*', $string)); # native
471 pack('V*', unpack('U*', $string)); # little-endian
473 pack('N*', unpack('U*', $string)); # big-endian
475 depending on the endianness required.
477 No UTF-32 encodings are implemented yet.
479 Both UCS-2 and UCS-4 style encodings can have "byte order marks" by
480 representing the code point 0xFFFE as the very first thing in a file.
482 =head2 Listing available encodings
484 use Encode qw(encodings);
487 Returns a list of the canonical names of the available encodings.
489 =head2 Defining Aliases
491 use Encode qw(define_alias);
492 define_alias( newName => ENCODING);
494 Allows newName to be used as am alias for ENCODING. ENCODING may be
495 either the name of an encoding or and encoding object (as above).
497 Currently I<newName> can be specified in the following ways:
501 =item As a simple string.
503 =item As a qr// compiled regular expression, e.g.:
505 define_alias( qr/^iso8859-(\d+)$/i => '"iso-8859-$1"' );
507 In this case if I<ENCODING> is not a reference it is C<eval>-ed to
508 allow C<$1> etc. to be subsituted. The example is one way to names as
509 used in X11 font names to alias the MIME names for the iso-8859-*
510 family. Note the double quote inside the single quote. If you are
511 using regex here, y ou have to do so or it won't work in this case.
513 =item As a code reference, e.g.:
515 define_alias( sub { return /^iso8859-(\d+)$/i ? "iso-8859-$1" : undef } , '');
517 In this case C<$_> will be set to the name that is being looked up and
518 I<ENCODING> is passed to the sub as its first argument. The example
519 is another way to names as used in X11 font names to alias the MIME
520 names for the iso-8859-* family.
524 =head2 Defining Encodings
526 use Encode qw(define_alias);
527 define_encoding( $object, 'canonicalName' [,alias...]);
529 Causes I<canonicalName> to be associated with I<$object>. The object
530 should provide the interface described in L</"IMPLEMENTATION CLASSES">
531 below. If more than two arguments are provided then additional
532 arguments are taken as aliases for I<$object> as for C<define_alias>.
534 =head1 Encoding and IO
536 It is very common to want to do encoding transformations when
537 reading or writing files, network connections, pipes etc.
538 If Perl is configured to use the new 'perlio' IO system then
539 C<Encode> provides a "layer" (See L<perliol>) which can transform
540 data as it is read or written.
542 Here is how the blind poet would modernise the encoding:
545 open(my $iliad,'<:encoding(iso-8859-7)','iliad.greek');
546 open(my $utf8,'>:utf8','iliad.utf8');
552 In addition the new IO system can also be configured to read/write
553 UTF-8 encoded characters (as noted above this is efficient):
555 open(my $fh,'>:utf8','anything');
556 print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
558 Either of the above forms of "layer" specifications can be made the default
559 for a lexical scope with the C<use open ...> pragma. See L<open>.
561 Once a handle is open is layers can be altered using C<binmode>.
563 Without any such configuration, or if Perl itself is built using
564 system's own IO, then write operations assume that file handle accepts
565 only I<bytes> and will C<die> if a character larger than 255 is
566 written to the handle. When reading, each octet from the handle
567 becomes a byte-in-a-character. Note that this default is the same
568 behaviour as bytes-only languages (including Perl before v5.6) would
569 have, and is sufficient to handle native 8-bit encodings
570 e.g. iso-8859-1, EBCDIC etc. and any legacy mechanisms for handling
571 other encodings and binary data.
573 In other cases it is the programs responsibility to transform
574 characters into bytes using the API above before doing writes, and to
575 transform the bytes read from a handle into characters before doing
576 "character operations" (e.g. C<lc>, C</\W+/>, ...).
578 You can also use PerlIO to convert larger amounts of data you don't
579 want to bring into memory. For example to convert between ISO-8859-1
580 (Latin 1) and UTF-8 (or UTF-EBCDIC in EBCDIC machines):
582 open(F, "<:encoding(iso-8859-1)", "data.txt") or die $!;
583 open(G, ">:utf8", "data.utf") or die $!;
584 while (<F>) { print G }
586 # Could also do "print G <F>" but that would pull
587 # the whole file into memory just to write it out again.
591 open(my $f, "<:encoding(cp1252)")
592 open(my $g, ">:encoding(iso-8859-2)")
593 open(my $h, ">:encoding(latin9)") # iso-8859-15
595 See L<PerlIO> for more information.
597 See also L<encoding> for how to change the default encoding of the
600 =head1 Encoding How to ...
606 =item * IO with mixed content (faking iso-2022-*)
608 Encode::JP implements its own iso-2022 routines, however.
610 =item * MIME's Content-Length:
612 =item * UTF-8 strings in binary data.
614 =item * Perl/Encode wrappers on non-Unicode XS modules.
618 =head1 Messing with Perl's Internals
620 The following API uses parts of Perl's internals in the current
621 implementation. As such they are efficient, but may change.
625 =item * is_utf8(STRING [, CHECK])
627 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
628 If CHECK is true, also checks the data in STRING for being well-formed
629 UTF-8. Returns true if successful, false otherwise.
635 [INTERNAL] Turn on the UTF-8 flag in STRING. The data in STRING is
636 B<not> checked for being well-formed UTF-8. Do not use unless you
637 B<know> that the STRING is well-formed UTF-8. Returns the previous
638 state of the UTF-8 flag (so please don't test the return value as
639 I<not> success or failure), or C<undef> if STRING is not a string.
645 [INTERNAL] Turn off the UTF-8 flag in STRING. Do not use frivolously.
646 Returns the previous state of the UTF-8 flag (so please don't test the
647 return value as I<not> success or failure), or C<undef> if STRING is
652 =head1 IMPLEMENTATION CLASSES
654 As mentioned above encodings are (in the current implementation at least)
655 defined by objects. The mapping of encoding name to object is via the
658 The values of the hash can currently be either strings or objects.
659 The string form may go away in the future. The string form occurs
660 when C<encodings()> has scanned C<@INC> for loadable encodings but has
661 not actually loaded the encoding in question. This is because the
662 current "loading" process is all Perl and a bit slow.
664 Once an encoding is loaded then value of the hash is object which
665 implements the encoding. The object should provide the following
672 Should return the string representing the canonical name of the encoding.
674 =item -E<gt>new_sequence
676 This is a placeholder for encodings with state. It should return an
677 object which implements this interface, all current implementations
678 return the original object.
680 =item -E<gt>encode($string,$check)
682 Should return the octet sequence representing I<$string>. If I<$check>
683 is true it should modify I<$string> in place to remove the converted
684 part (i.e. the whole string unless there is an error). If an error
685 occurs it should return the octet sequence for the fragment of string
686 that has been converted, and modify $string in-place to remove the
687 converted part leaving it starting with the problem fragment.
689 If check is is false then C<encode> should make a "best effort" to
690 convert the string - for example by using a replacement character.
692 =item -E<gt>decode($octets,$check)
694 Should return the string that I<$octets> represents. If I<$check> is
695 true it should modify I<$octets> in place to remove the converted part
696 (i.e. the whole sequence unless there is an error). If an error
697 occurs it should return the fragment of string that has been
698 converted, and modify $octets in-place to remove the converted part
699 leaving it starting with the problem fragment.
701 If check is is false then C<decode> should make a "best effort" to
702 convert the string - for example by using Unicode's "\x{FFFD}" as a
703 replacement character.
707 It should be noted that the check behaviour is different from the
708 outer public API. The logic is that the "unchecked" case is useful
709 when encoding is part of a stream which may be reporting errors
710 (e.g. STDERR). In such cases it is desirable to get everything
711 through somehow without causing additional errors which obscure the
712 original one. Also the encoding is best placed to know what the
713 correct replacement character is, so if that is the desired behaviour
714 then letting low level code do it is the most efficient.
716 In contrast if check is true, the scheme above allows the encoding to
717 do as much as it can and tell layer above how much that was. What is
718 lacking at present is a mechanism to report what went wrong. The most
719 likely interface will be an additional method call to the object, or
720 perhaps (to avoid forcing per-stream objects on otherwise stateless
721 encodings) and additional parameter.
723 It is also highly desirable that encoding classes inherit from
724 C<Encode::Encoding> as a base class. This allows that class to define
725 additional behaviour for all encoding objects. For example built in
726 Unicode, UCS-2 and UTF-8 classes use :
728 package Encode::MyEncoding;
729 use base qw(Encode::Encoding);
731 __PACKAGE__->Define(qw(myCanonical myAlias));
733 To create an object with bless {Name => ...},$class, and call
734 define_encoding. They inherit their C<name> method from
737 =head2 Compiled Encodings
739 F<Encode.xs> provides a class C<Encode::XS> which provides the
740 interface described above. It calls a generic octet-sequence to
741 octet-sequence "engine" that is driven by tables (defined in
742 F<encengine.c>). The same engine is used for both encode and
743 decode. C<Encode:XS>'s C<encode> forces Perl's characters to their
744 UTF-8 form and then treats them as just another multibyte
745 encoding. C<Encode:XS>'s C<decode> transforms the sequence and then
746 turns the UTF-8-ness flag as that is the form that the tables are
747 defined to produce. For details of the engine see the comments in
750 The tables are produced by the Perl script F<compile> (the name needs
751 to change so we can eventually install it somewhere). F<compile> can
752 currently read two formats:
758 This is a coined format used by Tcl. It is documented in
759 Encode/EncodeFormat.pod.
763 This is the semi-standard format used by IBM's ICU package.
767 F<compile> can write the following forms:
773 See above - the F<Encode/*.ucm> files provided with the distribution have
774 been created from the original Tcl .enc files using this approach.
778 Produces tables as C data structures - this is used to build in encodings
779 into F<Encode.so>/F<Encode.dll>.
783 In theory this allows encodings to be stand-alone loadable Perl
784 extensions. The process has not yet been tested. The plan is to use
785 this approach for large East Asian encodings.
789 The set of encodings built-in to F<Encode.so>/F<Encode.dll> is
790 determined by F<Makefile.PL>. The current set is as follows:
794 =item ascii and iso-8859-*
796 That is all the common 8-bit "western" encodings.
798 =item IBM-1047 and two other variants of EBCDIC.
800 These are the same variants that are supported by EBCDIC Perl as
801 "native" encodings. They are included to prove "reversibility" of
802 some constructs in EBCDIC Perl.
804 =item symbol and dingbats as used by Tk on X11.
806 (The reason Encode got started was to support Perl/Tk.)
810 That set is rather ad hoc and has been driven by the needs of the
811 tests rather than the needs of typical applications. It is likely
816 L<perlunicode>, L<perlebcdic>, L<perlfunc/open>, L<PerlIO>, L<encoding>,
817 L<utf8>, the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>