8 @ISA = qw(Exporter DynaLoader);
10 # Public, encouraged API is exported by default
34 # Documentation moved after __END__ for speed - NI-S
38 # The global hash is declared in XS code
39 $encoding{Unicode} = bless({},'Encode::Unicode');
40 $encoding{utf8} = bless({},'Encode::utf8');
41 $encoding{'iso10646-1'} = bless({},'Encode::iso10646_1');
46 foreach my $dir (@INC)
48 if (opendir(my $dh,"$dir/Encode"))
50 while (defined(my $name = readdir($dh)))
52 if ($name =~ /^(.*)\.enc$/)
54 next if exists $encoding{$1};
55 $encoding{$1} = "$dir/$name";
61 return keys %encoding;
66 my ($class,$name,$file) = @_;
67 if (open(my $fh,$file))
73 $type = substr($line,0,1);
74 last unless $type eq '#';
76 $class .= ('::'.(($type eq 'E') ? 'Escape' : 'Table'));
77 #warn "Loading $file";
78 return $class->read($fh,$name,$type);
88 my ($class,$name) = @_;
90 unless (ref($enc = $encoding{$name}))
92 $enc = $class->loadEncoding($name,$enc) if defined $enc;
95 foreach my $dir (@INC)
97 last if ($enc = $class->loadEncoding($name,"$dir/Encode/$name.enc"));
100 $encoding{$name} = $enc;
108 return __PACKAGE__->getEncoding($name);
113 my ($name,$string,$check) = @_;
114 my $enc = find_encoding($name);
115 croak("Unknown encoding '$name'") unless defined $enc;
116 my $octets = $enc->encode($string,$check);
117 return undef if ($check && length($string));
123 my ($name,$octets,$check) = @_;
124 my $enc = find_encoding($name);
125 croak("Unknown encoding '$name'") unless defined $enc;
126 my $string = $enc->decode($octets,$check);
127 return undef if ($check && length($octets));
133 my ($string,$from,$to,$check) = @_;
134 my $f = find_encoding($from);
135 croak("Unknown encoding '$from'") unless defined $f;
136 my $t = find_encoding($to);
137 croak("Unknown encoding '$to'") unless defined $t;
138 my $uni = $f->decode($string,$check);
139 return undef if ($check && length($string));
140 $string = $t->encode($uni,$check);
141 return undef if ($check && length($uni));
142 return length($_[0] = $string);
155 return undef unless utf8_decode($str);
159 package Encode::Encoding;
160 # Base class for classes which implement encodings
162 # Temporary legacy methods
163 sub toUnicode { shift->decode(@_) }
164 sub fromUnicode { shift->encode(@_) }
166 sub new_sequence { return $_[0] }
169 use base 'Encode::Encoding';
171 package Encode::Unicode;
172 use base 'Encode::Encoding';
174 # Dummy package that provides the encode interface but leaves data
175 # as UTF-8 encoded. It is here so that from_to() works.
177 sub name { 'Unicode' }
181 my ($obj,$str,$chk) = @_;
182 Encode::utf8_upgrade($str);
189 package Encode::utf8;
190 use base 'Encode::Encoding';
192 # package to allow long-hand
193 # $octets = encode( utf8 => $string );
200 my ($obj,$octets,$chk) = @_;
201 my $str = Encode::decode_utf8($octets);
212 my ($obj,$string,$chk) = @_;
213 my $octets = Encode::encode_utf8($string);
218 package Encode::Table;
219 use base 'Encode::Encoding';
223 my ($class,$fh,$name,$type) = @_;
224 my $rep = $class->can("rep_$type");
225 my ($def,$sym,$pages) = split(/\s+/,scalar(<$fh>));
234 my $page = hex($line);
236 my $ch = $page * 256;
237 for (my $i = 0; $i < 16; $i++)
240 for (my $j = 0; $j < 16; $j++)
242 my $val = hex(substr($line,0,4,''));
257 $touni[$page] = \@page;
260 return bless {Name => $name,
269 sub name { shift->{'Name'} }
275 sub rep_M { ($_[0] > 255) ? 'n' : 'C' }
280 $ch = 0 unless @_ > 1;
286 my ($obj,$str,$chk) = @_;
287 my $rep = $obj->{'Rep'};
288 my $touni = $obj->{'ToUni'};
292 my $ch = ord(substr($str,0,1,''));
294 if (&$rep($ch) eq 'C')
296 $x = $touni->[0][$ch];
300 $x = $touni->[$ch][ord(substr($str,0,1,''))];
305 # What do we do here ?
310 $_[1] = $str if $chk;
316 my ($obj,$uni,$chk) = @_;
317 my $fmuni = $obj->{'FmUni'};
319 my $def = $obj->{'Def'};
320 my $rep = $obj->{'Rep'};
323 my $ch = substr($uni,0,1,'');
324 my $x = $fmuni->{chr(ord($ch))};
330 $str .= pack(&$rep($x),$x);
332 $_[1] = $uni if $chk;
336 package Encode::iso10646_1;
337 use base 'Encode::Encoding';
339 # Encoding is 16-bit network order Unicode
340 # Used for X font encodings
342 sub name { 'iso10646-1' }
346 my ($obj,$str,$chk) = @_;
350 my $code = unpack('n',substr($str,0,2,'')) & 0xffff;
353 $_[1] = $str if $chk;
354 Encode::utf8_upgrade($uni);
360 my ($obj,$uni,$chk) = @_;
364 my $ch = substr($uni,0,1,'');
371 $str .= pack('n',$x);
373 $_[1] = $uni if $chk;
378 package Encode::Escape;
379 use base 'Encode::Encoding';
385 my ($class,$fh,$name) = @_;
386 my %self = (Name => $name, Num => 0);
389 my ($key,$val) = /^(\S+)\s+(.*)$/;
390 $val =~ s/^\{(.*?)\}/$1/g;
391 $val =~ s/\\x([0-9a-f]{2})/chr(hex($1))/ge;
394 return bless \%self,$class;
397 sub name { shift->{'Name'} }
401 croak("Not implemented yet");
406 croak("Not implemented yet");
409 # switch back to Encode package in case we ever add AutoLoader
418 Encode - character encodings
426 The C<Encode> module provides the interfaces between perl's strings
427 and the rest of the system. Perl strings are sequences of B<characters>.
429 The repertoire of characters that Perl can represent is at least that
430 defined by the Unicode Consortium. On most platforms the ordinal values
431 of the characters (as returned by C<ord(ch)>) is the "Unicode codepoint" for
432 the character (the exceptions are those platforms where the legacy
433 encoding is some variant of EBCDIC rather than a super-set of ASCII
434 - see L<perlebcdic>).
436 Traditionaly computer data has been moved around in 8-bit chunks
437 often called "bytes". These chunks are also known as "octets" in
438 networking standards. Perl is widely used to manipulate data of
439 many types - not only strings of characters representing human or
440 computer languages but also "binary" data being the machines representation
441 of numbers, pixels in an image - or just about anything.
443 When perl is processing "binary data" the programmer wants perl to process
444 "sequences of bytes". This is not a problem for perl - as a byte has 256
445 possible values it easily fits in perl's much larger "logical character".
453 I<character>: a character in the range 0..(2**32-1) (or more).
454 (What perl's strings are made of.)
458 I<byte>: a character in the range 0..255
459 (A special case of a perl character.)
463 I<octet>: 8 bits of data, with ordinal values 0..255
464 (Term for bytes passed to or from a non-perl context, e.g. disk file.)
468 The marker [INTERNAL] marks Internal Implementation Details, in
469 general meant only for those who think they know what they are doing,
470 and such details may change in future releases.
474 =head2 Characteristics of an Encoding
476 An encoding has a "repertoire" of characters that it can represent,
477 and for each representable character there is at least one sequence of
478 octets that represents it.
480 =head2 Types of Encodings
482 Encodings can be divided into the following types:
486 =item * Fixed length 8-bit (or less) encodings.
488 Each character is a single octet so may have a repertoire of up to
489 256 characters. ASCII and iso-8859-* are typical examples.
491 =item * Fixed length 16-bit encodings
493 Each character is two octets so may have a repertoire of up to
494 65,536 characters. Unicode's UCS-2 is an example. Also used for
495 encodings for East Asian languages.
497 =item * Fixed length 32-bit encodings.
499 Not really very "encoded" encodings. The Unicode code points
500 are just represented as 4-octet integers. None the less because
501 different architectures use different representations of integers
502 (so called "endian") there at least two disctinct encodings.
504 =item * Multi-byte encodings
506 The number of octets needed to represent a character varies.
507 UTF-8 is a particularly complex but regular case of a multi-byte
508 encoding. Several East Asian countries use a multi-byte encoding
509 where 1-octet is used to cover western roman characters and Asian
510 characters get 2-octets.
511 (UTF-16 is strictly a multi-byte encoding taking either 2 or 4 octets
512 to represent a Unicode code point.)
514 =item * "Escape" encodings.
516 These encodings embed "escape sequences" into the octet sequence
517 which describe how the following octets are to be interpreted.
518 The iso-2022-* family is typical. Following the escape sequence
519 octets are encoded by an "embedded" encoding (which will be one
520 of the above types) until another escape sequence switches to
521 a different "embedded" encoding.
523 These schemes are very flexible and can handle mixed languages but are
524 very complex to process (and have state).
525 No escape encodings are implemented for perl yet.
529 =head2 Specifying Encodings
531 Encodings can be specified to the API described below in two ways:
537 Encoding names are strings with characters taken from a restricted repertoire.
538 See L</"Encoding Names">.
540 =item 2. As an object
542 Encoding objects are returned by C<find_encoding($name)>.
546 =head2 Encoding Names
548 Encoding names are case insensitive. White space in names is ignored.
549 In addition an encoding may have aliases. Each encoding has one "canonical" name.
550 The "canonical" name is chosen from the names of the encoding by picking
551 the first in the following sequence:
555 =item * The MIME name as defined in IETF RFC-XXXX.
557 =item * The name in the IANA registry.
559 =item * The name used by the the organization that defined it.
563 Because of all the alias issues, and because in the general case
564 encodings have state C<Encode> uses the encoding object internally
565 once an operation is in progress.
567 I<Aliasing is not yet implemented.>
569 =head1 PERL ENCODING API
571 =head2 Generic Encoding Interface
577 $bytes = encode(ENCODING, $string[, CHECK])
579 Encodes string from perl's internal form into I<ENCODING> and returns a
581 See L</"Handling Malformed Data">.
585 $string = decode(ENCODING, $bytes[, CHECK])
587 Decode sequence of octets assumed to be in I<ENCODING> into perls internal
588 form and returns the resuting string.
589 See L</"Handling Malformed Data">.
593 =head2 Handling Malformed Data
595 If CHECK is not set, C<undef> is returned. If the data is supposed to
596 be UTF-8, an optional lexical warning (category utf8) is given.
597 If CHECK is true but not a code reference, dies.
599 It would desirable to have a way to indicate that transform should use the
600 encodings "replacement character" - no such mechanism is defined yet.
602 It is also planned to allow I<CHECK> to be a code reference.
604 This is not yet implemented as there are design issues with what its arguments
605 should be and how it returns its results.
611 Passed remaining fragment of string being processed.
612 Modifies it in place to remove bytes/characters it can understand
613 and returns a string used to represent them.
617 my $ch = substr($_[0],0,1,'');
618 return sprintf("\x{%02X}",ord($ch);
621 This scheme is close to how underlying C code for Encode works, but gives
622 the fixup routine very little context.
626 Passed original string, and an index into it of the problem area,
627 and output string so far.
628 Appends what it will to output string and returns new index into
633 # my ($s,$i,$d) = @_;
634 my $ch = substr($_[0],$_[1],1);
635 $_[2] .= sprintf("\x{%02X}",ord($ch);
639 This scheme gives maximal control to the fixup routine but is more complicated
640 to code, and may need internals of Encode to be tweaked to keep original
647 Multiple return values rather than in-place modifications.
649 Index into the string could be pos($str) allowing s/\G...//.
655 The Unicode consortium defines the UTF-8 standard as a way of encoding
656 the entire Unicode repertiore as sequences of octets. This encoding
657 is expected to become very widespread. Perl can use this form internaly
658 to represent strings, so conversions to and from this form are particularly
659 efficient (as octets in memory do not have to change, just the meta-data
660 that tells perl how to treat them).
666 $bytes = encode_utf8($string);
668 The characters that comprise string are encoded in perl's superset of UTF-8
669 and the resulting octets returned as a sequence of bytes. All possible
670 characters have a UTF-8 representation so this function cannot fail.
674 $string = decode_utf8($bytes [,CHECK]);
676 The sequence of octets represented by $bytes is decoded from UTF-8 into
677 a sequence of logical characters. Not all sequences of octets form valid
678 UTF-8 encodings, so it is possible for this call to fail.
679 See L</"Handling Malformed Data">.
683 =head2 Other Encodings of Unicode
685 UTF-16 is similar to UCS-2, 16 bit or 2-byte chunks.
686 UCS-2 can only represent 0..0xFFFF, while UTF-16 has a "surogate pair"
687 scheme which allows it to cover the whole Unicode range.
689 Encode implements big-endian UCS-2 as the encoding "iso10646-1" as that
690 happens to be the name used by that representation when used with X11 fonts.
692 UTF-32 or UCS-4 is 32-bit or 4-byte chunks. Perl's logical characters
693 can be considered as being in this form without encoding. An encoding
694 to transfer strings in this form (e.g. to write them to a file) would need to
696 pack('L',map(chr($_),split(//,$string))); # native
698 pack('V',map(chr($_),split(//,$string))); # little-endian
700 pack('N',map(chr($_),split(//,$string))); # big-endian
702 depending on the endian required.
704 No UTF-32 encodings are not yet implemented.
706 Both UCS-2 and UCS-4 style encodings can have "byte order marks" by representing
707 the code point 0xFFFE as the very first thing in a file.
709 =head1 Encoding and IO
711 It is very common to want to do encoding transformations when
712 reading or writing files, network connections, pipes etc.
713 If perl is configured to use the new 'perlio' IO system then
714 C<Encode> provides a "layer" (See L<perliol>) which can transform
715 data as it is read or written.
717 open(my $ilyad,'>:encoding(iso8859-7)','ilyad.greek');
720 In addition the new IO system can also be configured to read/write
721 UTF-8 encoded characters (as noted above this is efficient):
723 open(my $fh,'>:utf8','anything');
724 print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
726 Either of the above forms of "layer" specifications can be made the default
727 for a lexical scope with the C<use open ...> pragma. See L<open>.
729 Once a handle is open is layers can be altered using C<binmode>.
731 Without any such configuration, or if perl itself is built using
732 system's own IO, then write operations assume that file handle accepts
733 only I<bytes> and will C<die> if a character larger than 255 is
734 written to the handle. When reading, each octet from the handle
735 becomes a byte-in-a-character. Note that this default is the same
736 behaviour as bytes-only languages (including perl before v5.6) would have,
737 and is sufficient to handle native 8-bit encodings e.g. iso-8859-1,
738 EBCDIC etc. and any legacy mechanisms for handling other encodings
741 In other cases it is the programs responsibility
742 to transform characters into bytes using the API above before
743 doing writes, and to transform the bytes read from a handle into characters
744 before doing "character operations" (e.g. C<lc>, C</\W+/>, ...).
746 =head1 Encoding How to ...
752 =item * IO with mixed content (faking iso-2020-*)
754 =item * MIME's Content-Length:
756 =item * UTF-8 strings in binary data.
758 =item * perl/Encode wrappers on non-Unicode XS modules.
762 =head1 Messing with Perl's Internals
764 The following API uses parts of perl's internals in the current implementation.
765 As such they are efficient, but may change.
771 $num_octets = utf8_upgrade($string);
773 Converts internal representation of string to the UTF-8 form.
774 Returns the number of octets necessary to represent the string as UTF-8.
776 =item * utf8_downgrade($string[, CHECK])
778 Converts internal representation of string to be un-encoded bytes.
780 =item * is_utf8(STRING [, CHECK])
782 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
783 If CHECK is true, also checks the data in STRING for being
784 well-formed UTF-8. Returns true if successful, false otherwise.
786 =item * valid_utf8(STRING)
788 [INTERNAL] Test whether STRING is in a consistent state.
789 Will return true if string is held as bytes, or is well-formed UTF-8
790 and has the UTF-8 flag on.
791 Main reason for this routine is to allow perl's testsuite to check
792 that operations have left strings in a consistent state.
798 [INTERNAL] Turn on the UTF-8 flag in STRING. The data in STRING is
799 B<not> checked for being well-formed UTF-8. Do not use unless you
800 B<know> that the STRING is well-formed UTF-8. Returns the previous
801 state of the UTF-8 flag (so please don't test the return value as
802 I<not> success or failure), or C<undef> if STRING is not a string.
808 [INTERNAL] Turn off the UTF-8 flag in STRING. Do not use frivolously.
809 Returns the previous state of the UTF-8 flag (so please don't test the
810 return value as I<not> success or failure), or C<undef> if STRING is
815 =head1 IMPLEMENTATION CLASSES
817 As mentioned above encodings are (in the current implementation at least)
818 defined by objects. The mapping of encoding name to object is via the
819 C<%Encode::encodings> hash. (It is a package hash to allow XS code to get
822 The values of the hash can currently be either strings or objects.
823 The string form may go away in the future. The string form occurs
824 when C<encodings()> has scanned C<@INC> for loadable encodings but has
825 not actually loaded the encoding in question. This is because the
826 current "loading" process is all perl and a bit slow.
828 Once an encoding is loaded then value of the hash is object which implements
829 the encoding. The object should provide the following interface:
835 Should return the string representing the canonical name of the encoding.
837 =item -E<gt>new_sequence
839 This is a placeholder for encodings with state. It should return an object
840 which implements this interface, all current implementations return the
843 =item -E<gt>encode($string,$check)
845 Should return the octet sequence representing I<$string>. If I<$check> is true
846 it should modify I<$string> in place to remove the converted part (i.e.
847 the whole string unless there is an error).
848 If an error occurs it should return the octet sequence for the
849 fragment of string that has been converted, and modify $string in-place
850 to remove the converted part leaving it starting with the problem fragment.
852 If check is is false then C<encode> should make a "best effort" to convert
853 the string - for example by using a replacement character.
855 =item -E<gt>decode($octets,$check)
857 Should return the string that I<$octets> represents. If I<$check> is true
858 it should modify I<$octets> in place to remove the converted part (i.e.
859 the whole sequence unless there is an error).
860 If an error occurs it should return the fragment of string
861 that has been converted, and modify $octets in-place to remove the converted part
862 leaving it starting with the problem fragment.
864 If check is is false then C<decode> should make a "best effort" to convert
865 the string - for example by using Unicode's "\x{FFFD}" as a replacement character.
869 It should be noted that the check behaviour is different from the outer
870 public API. The logic is that the "unchecked" case is useful when
871 encoding is part of a stream which may be reporting errors (e.g. STDERR).
872 In such cases it is desirable to get everything through somehow without
873 causing additional errors which obscure the original one. Also the encoding
874 is best placed to know what the correct replacement character is, so if that
875 is the desired behaviour then letting low level code do it is the most efficient.
877 In contrast if check is true, the scheme above allows the encoding to do as
878 much as it can and tell layer above how much that was. What is lacking
879 at present is a mechanism to report what went wrong. The most likely interface
880 will be an additional method call to the object, or perhaps
881 (to avoid forcing per-stream objects on otherwise stateless encodings)
882 and additional parameter.
884 It is also highly desirable that encoding classes inherit from C<Encode::Encoding>
885 as a base class. This allows that class to define additional behaviour for
886 all encoding objects.
888 =head2 Compiled Encodings
890 F<Encode.xs> provides a class C<Encode::XS> which provides the interface described
891 above. It calls a generic octet-sequence to octet-sequence "engine" that is
892 driven by tables (defined in F<encengine.c>). The same engine is used for both
893 encode and decode. C<Encode:XS>'s C<encode> forces perl's characters to their UTF-8 form
894 and then treats them as just another multibyte encoding. C<Encode:XS>'s C<decode> transforms
895 the sequence and then turns the UTF-8-ness flag as that is the form that the tables
896 are defined to produce. For details of the engine see the comments in F<encengine.c>.
898 The tables are produced by the perl script F<compile> (the name needs to change so
899 we can eventually install it somewhere). F<compile> can currently read two formats:
905 This is a coined format used by Tcl. It is documented in Encode/EncodeFormat.pod.
909 This is the semi-standard format used by IBM's ICU package.
913 F<compile> can write the following forms:
919 See above - the F<Encode/*.ucm> files provided with the distribution have
920 been created from the original Tcl .enc files using this approach.
924 Produces tables as C data structures - this is used to build in encodings
925 into F<Encode.so>/F<Encode.dll>.
929 In theory this allows encodings to be stand-alone loadable perl extensions.
930 The process has not yet been tested. The plan is to use this approach
931 for large East Asian encodings.
935 The set of encodings built-in to F<Encode.so>/F<Encode.dll> is determined by
936 F<Makefile.PL>. The current set is as follows:
940 =item ascii and iso-8859-*
942 That is all the common 8-bit "western" encodings.
944 =item IBM-1047 and two other variants of EBCDIC.
946 These are the same variants that are supported by EBCDIC perl as "native" encodings.
947 They are included to prove "reversibility" of some constructs in EBCDIC perl.
949 =item symbol and dingbats as used by Tk on X11.
951 (The reason Encode got started was to support perl/Tk.)
955 That set is rather ad. hoc. and has been driven by the needs of the tests rather
956 than the needs of typical applications. It is likely to be rationalized.
960 L<perlunicode>, L<perlebcdic>, L<perlfunc/open>