9 our @ISA = qw(Exporter DynaLoader);
11 # Public, encouraged API is exported by default
37 # Documentation moved after __END__ for speed - NI-S
41 # Make a %encoding package variable to allow a certain amount of cheating
43 my @alias; # ordered matching list
44 my %alias; # cached known aliases
49 return keys %encoding;
56 unless (exists $alias{$_})
58 for (my $i=0; $i < @alias; $i += 2)
60 my $alias = $alias[$i];
61 my $val = $alias[$i+1];
63 if (ref($alias) eq 'Regexp' && $_ =~ $alias)
67 elsif (ref($alias) eq 'CODE')
69 $new = &{$alias}($val)
71 elsif (lc($_) eq $alias)
77 next if $new eq $_; # avoid (direct) recursion on bugs
78 my $enc = (ref($new)) ? $new : find_encoding($new);
94 my ($alias,$name) = splice(@_,0,2);
95 push(@alias, $alias => $name);
99 # Allow variants of iso-8859-1 etc.
100 define_alias( qr/^iso[-_]?(\d+)[-_](\d+)$/i => '"iso-$1-$2"' );
102 # Allow latin-1 style names as well
103 # 0 1 2 3 4 5 6 7 8 9 10
104 my @latin2iso_num = ( 0, 1, 2, 3, 4, 9, 10, 13, 14, 15, 16 );
105 define_alias( qr/^latin[-_]?(\d+)$/i => '"iso-8859-$latin2iso_num[$1]"' );
107 # Common names for non-latin prefered MIME names
108 define_alias( 'ascii' => 'US-ascii',
109 'cyrillic' => 'iso-8859-5',
110 'arabic' => 'iso-8859-6',
111 'greek' => 'iso-8859-7',
112 'hebrew' => 'iso-8859-8');
114 define_alias( 'ibm-1047' => 'cp1047');
116 # Map white space and _ to '-'
117 define_alias( qr/^(\S+)[\s_]+(.*)$/i => '"$1-$2"' );
123 $encoding{$name} = $obj;
125 define_alias($lc => $obj) unless $lc eq $name;
129 define_alias($alias,$obj);
136 my ($class,$name) = @_;
138 if (exists $encoding{$name})
140 return $encoding{$name};
144 return $class->findAlias($name);
151 return __PACKAGE__->getEncoding($name);
156 my ($name,$string,$check) = @_;
157 my $enc = find_encoding($name);
158 croak("Unknown encoding '$name'") unless defined $enc;
159 my $octets = $enc->encode($string,$check);
160 return undef if ($check && length($string));
166 my ($name,$octets,$check) = @_;
167 my $enc = find_encoding($name);
168 croak("Unknown encoding '$name'") unless defined $enc;
169 my $string = $enc->decode($octets,$check);
170 return undef if ($check && length($octets));
176 my ($string,$from,$to,$check) = @_;
177 my $f = find_encoding($from);
178 croak("Unknown encoding '$from'") unless defined $f;
179 my $t = find_encoding($to);
180 croak("Unknown encoding '$to'") unless defined $t;
181 my $uni = $f->decode($string,$check);
182 return undef if ($check && length($string));
183 $string = $t->encode($uni,$check);
184 return undef if ($check && length($uni));
185 return length($_[0] = $string);
198 return undef unless utf8_decode($str);
202 package Encode::Encoding;
203 # Base class for classes which implement encodings
208 my $canonical = shift;
209 $obj = bless { Name => $canonical },$obj unless ref $obj;
210 # warn "$canonical => $obj\n";
211 Encode::define_encoding($obj, $canonical, @_);
214 sub name { shift->{'Name'} }
216 # Temporary legacy methods
217 sub toUnicode { shift->decode(@_) }
218 sub fromUnicode { shift->encode(@_) }
220 sub new_sequence { return $_[0] }
223 use base 'Encode::Encoding';
225 package Encode::Unicode;
226 use base 'Encode::Encoding';
228 # Dummy package that provides the encode interface but leaves data
229 # as UTF-8 encoded. It is here so that from_to() works.
231 __PACKAGE__->Define('Unicode');
235 my ($obj,$str,$chk) = @_;
236 Encode::utf8_upgrade($str);
243 package Encode::utf8;
244 use base 'Encode::Encoding';
245 # package to allow long-hand
246 # $octets = encode( utf8 => $string );
249 __PACKAGE__->Define(qw(UTF-8 utf8));
253 my ($obj,$octets,$chk) = @_;
254 my $str = Encode::decode_utf8($octets);
265 my ($obj,$string,$chk) = @_;
266 my $octets = Encode::encode_utf8($string);
271 package Encode::iso10646_1;
272 use base 'Encode::Encoding';
273 # Encoding is 16-bit network order Unicode (no surogates)
274 # Used for X font encodings
276 __PACKAGE__->Define(qw(UCS-2 iso10646-1));
280 my ($obj,$str,$chk) = @_;
284 my $code = unpack('n',substr($str,0,2,'')) & 0xffff;
287 $_[1] = $str if $chk;
288 Encode::utf8_upgrade($uni);
294 my ($obj,$uni,$chk) = @_;
298 my $ch = substr($uni,0,1,'');
305 $str .= pack('n',$x);
307 $_[1] = $uni if $chk;
311 # switch back to Encode package in case we ever add AutoLoader
320 Encode - character encodings
328 The C<Encode> module provides the interfaces between perl's strings
329 and the rest of the system. Perl strings are sequences of B<characters>.
331 The repertoire of characters that Perl can represent is at least that
332 defined by the Unicode Consortium. On most platforms the ordinal values
333 of the characters (as returned by C<ord(ch)>) is the "Unicode codepoint" for
334 the character (the exceptions are those platforms where the legacy
335 encoding is some variant of EBCDIC rather than a super-set of ASCII
336 - see L<perlebcdic>).
338 Traditionaly computer data has been moved around in 8-bit chunks
339 often called "bytes". These chunks are also known as "octets" in
340 networking standards. Perl is widely used to manipulate data of
341 many types - not only strings of characters representing human or
342 computer languages but also "binary" data being the machines representation
343 of numbers, pixels in an image - or just about anything.
345 When perl is processing "binary data" the programmer wants perl to process
346 "sequences of bytes". This is not a problem for perl - as a byte has 256
347 possible values it easily fits in perl's much larger "logical character".
355 I<character>: a character in the range 0..(2**32-1) (or more).
356 (What perl's strings are made of.)
360 I<byte>: a character in the range 0..255
361 (A special case of a perl character.)
365 I<octet>: 8 bits of data, with ordinal values 0..255
366 (Term for bytes passed to or from a non-perl context, e.g. disk file.)
370 The marker [INTERNAL] marks Internal Implementation Details, in
371 general meant only for those who think they know what they are doing,
372 and such details may change in future releases.
376 =head2 Characteristics of an Encoding
378 An encoding has a "repertoire" of characters that it can represent,
379 and for each representable character there is at least one sequence of
380 octets that represents it.
382 =head2 Types of Encodings
384 Encodings can be divided into the following types:
388 =item * Fixed length 8-bit (or less) encodings.
390 Each character is a single octet so may have a repertoire of up to
391 256 characters. ASCII and iso-8859-* are typical examples.
393 =item * Fixed length 16-bit encodings
395 Each character is two octets so may have a repertoire of up to
396 65,536 characters. Unicode's UCS-2 is an example. Also used for
397 encodings for East Asian languages.
399 =item * Fixed length 32-bit encodings.
401 Not really very "encoded" encodings. The Unicode code points
402 are just represented as 4-octet integers. None the less because
403 different architectures use different representations of integers
404 (so called "endian") there at least two disctinct encodings.
406 =item * Multi-byte encodings
408 The number of octets needed to represent a character varies.
409 UTF-8 is a particularly complex but regular case of a multi-byte
410 encoding. Several East Asian countries use a multi-byte encoding
411 where 1-octet is used to cover western roman characters and Asian
412 characters get 2-octets.
413 (UTF-16 is strictly a multi-byte encoding taking either 2 or 4 octets
414 to represent a Unicode code point.)
416 =item * "Escape" encodings.
418 These encodings embed "escape sequences" into the octet sequence
419 which describe how the following octets are to be interpreted.
420 The iso-2022-* family is typical. Following the escape sequence
421 octets are encoded by an "embedded" encoding (which will be one
422 of the above types) until another escape sequence switches to
423 a different "embedded" encoding.
425 These schemes are very flexible and can handle mixed languages but are
426 very complex to process (and have state).
427 No escape encodings are implemented for perl yet.
431 =head2 Specifying Encodings
433 Encodings can be specified to the API described below in two ways:
439 Encoding names are strings with characters taken from a restricted repertoire.
440 See L</"Encoding Names">.
442 =item 2. As an object
444 Encoding objects are returned by C<find_encoding($name)>.
448 =head2 Encoding Names
450 Encoding names are case insensitive. White space in names is ignored.
451 In addition an encoding may have aliases. Each encoding has one "canonical" name.
452 The "canonical" name is chosen from the names of the encoding by picking
453 the first in the following sequence:
457 =item * The MIME name as defined in IETF RFC-XXXX.
459 =item * The name in the IANA registry.
461 =item * The name used by the the organization that defined it.
465 Because of all the alias issues, and because in the general case
466 encodings have state C<Encode> uses the encoding object internally
467 once an operation is in progress.
469 =head1 PERL ENCODING API
471 =head2 Generic Encoding Interface
477 $bytes = encode(ENCODING, $string[, CHECK])
479 Encodes string from perl's internal form into I<ENCODING> and returns a
481 See L</"Handling Malformed Data">.
485 $string = decode(ENCODING, $bytes[, CHECK])
487 Decode sequence of octets assumed to be in I<ENCODING> into perls internal
488 form and returns the resuting string.
489 See L</"Handling Malformed Data">.
493 =head2 Handling Malformed Data
495 If CHECK is not set, C<undef> is returned. If the data is supposed to
496 be UTF-8, an optional lexical warning (category utf8) is given.
497 If CHECK is true but not a code reference, dies.
499 It would desirable to have a way to indicate that transform should use the
500 encodings "replacement character" - no such mechanism is defined yet.
502 It is also planned to allow I<CHECK> to be a code reference.
504 This is not yet implemented as there are design issues with what its arguments
505 should be and how it returns its results.
511 Passed remaining fragment of string being processed.
512 Modifies it in place to remove bytes/characters it can understand
513 and returns a string used to represent them.
517 my $ch = substr($_[0],0,1,'');
518 return sprintf("\x{%02X}",ord($ch);
521 This scheme is close to how underlying C code for Encode works, but gives
522 the fixup routine very little context.
526 Passed original string, and an index into it of the problem area,
527 and output string so far.
528 Appends what it will to output string and returns new index into
533 # my ($s,$i,$d) = @_;
534 my $ch = substr($_[0],$_[1],1);
535 $_[2] .= sprintf("\x{%02X}",ord($ch);
539 This scheme gives maximal control to the fixup routine but is more complicated
540 to code, and may need internals of Encode to be tweaked to keep original
547 Multiple return values rather than in-place modifications.
549 Index into the string could be pos($str) allowing s/\G...//.
555 The Unicode consortium defines the UTF-8 standard as a way of encoding
556 the entire Unicode repertiore as sequences of octets. This encoding
557 is expected to become very widespread. Perl can use this form internaly
558 to represent strings, so conversions to and from this form are particularly
559 efficient (as octets in memory do not have to change, just the meta-data
560 that tells perl how to treat them).
566 $bytes = encode_utf8($string);
568 The characters that comprise string are encoded in perl's superset of UTF-8
569 and the resulting octets returned as a sequence of bytes. All possible
570 characters have a UTF-8 representation so this function cannot fail.
574 $string = decode_utf8($bytes [,CHECK]);
576 The sequence of octets represented by $bytes is decoded from UTF-8 into
577 a sequence of logical characters. Not all sequences of octets form valid
578 UTF-8 encodings, so it is possible for this call to fail.
579 See L</"Handling Malformed Data">.
583 =head2 Other Encodings of Unicode
585 UTF-16 is similar to UCS-2, 16 bit or 2-byte chunks.
586 UCS-2 can only represent 0..0xFFFF, while UTF-16 has a "surogate pair"
587 scheme which allows it to cover the whole Unicode range.
589 Encode implements big-endian UCS-2 aliased to "iso10646-1" as that
590 happens to be the name used by that representation when used with X11 fonts.
592 UTF-32 or UCS-4 is 32-bit or 4-byte chunks. Perl's logical characters
593 can be considered as being in this form without encoding. An encoding
594 to transfer strings in this form (e.g. to write them to a file) would need to
596 pack('L',map(chr($_),split(//,$string))); # native
598 pack('V',map(chr($_),split(//,$string))); # little-endian
600 pack('N',map(chr($_),split(//,$string))); # big-endian
602 depending on the endian required.
604 No UTF-32 encodings are implemented yet.
606 Both UCS-2 and UCS-4 style encodings can have "byte order marks" by representing
607 the code point 0xFFFE as the very first thing in a file.
609 =head2 Listing available encodings
611 use Encode qw(encodings);
614 Returns a list of the canonical names of the available encodings.
616 =head2 Defining Aliases
618 use Encode qw(define_alias);
619 define_alias( newName => ENCODING);
621 Allows newName to be used as am alias for ENCODING. ENCODING may be either the
622 name of an encoding or and encoding object (as above).
624 Currently I<newName> can be specified in the following ways:
628 =item As a simple string.
630 =item As a qr// compiled regular expression, e.g.:
632 define_alias( qr/^iso8859-(\d+)$/i => '"iso-8859-$1"' );
634 In this case if I<ENCODING> is not a reference it is C<eval>-ed to allow
635 C<$1> etc. to be subsituted.
636 The example is one way to names as used in X11 font names to alias the MIME names for the
639 =item As a code reference, e.g.:
641 define_alias( sub { return /^iso8859-(\d+)$/i ? "iso-8859-$1" : undef } , '');
643 In this case C<$_> will be set to the name that is being looked up and
644 I<ENCODING> is passed to the sub as its first argument.
645 The example is another way to names as used in X11 font names to alias the MIME names for
646 the iso-8859-* family.
650 =head2 Defining Encodings
652 use Encode qw(define_alias);
653 define_encoding( $object, 'canonicalName' [,alias...]);
655 Causes I<canonicalName> to be associated with I<$object>.
656 The object should provide the interface described in L</"IMPLEMENTATION CLASSES"> below.
657 If more than two arguments are provided then additional arguments are taken
658 as aliases for I<$object> as for C<define_alias>.
660 =head1 Encoding and IO
662 It is very common to want to do encoding transformations when
663 reading or writing files, network connections, pipes etc.
664 If perl is configured to use the new 'perlio' IO system then
665 C<Encode> provides a "layer" (See L<perliol>) which can transform
666 data as it is read or written.
668 open(my $ilyad,'>:encoding(iso-8859-7)','ilyad.greek');
671 In addition the new IO system can also be configured to read/write
672 UTF-8 encoded characters (as noted above this is efficient):
674 open(my $fh,'>:utf8','anything');
675 print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
677 Either of the above forms of "layer" specifications can be made the default
678 for a lexical scope with the C<use open ...> pragma. See L<open>.
680 Once a handle is open is layers can be altered using C<binmode>.
682 Without any such configuration, or if perl itself is built using
683 system's own IO, then write operations assume that file handle accepts
684 only I<bytes> and will C<die> if a character larger than 255 is
685 written to the handle. When reading, each octet from the handle
686 becomes a byte-in-a-character. Note that this default is the same
687 behaviour as bytes-only languages (including perl before v5.6) would have,
688 and is sufficient to handle native 8-bit encodings e.g. iso-8859-1,
689 EBCDIC etc. and any legacy mechanisms for handling other encodings
692 In other cases it is the programs responsibility
693 to transform characters into bytes using the API above before
694 doing writes, and to transform the bytes read from a handle into characters
695 before doing "character operations" (e.g. C<lc>, C</\W+/>, ...).
697 =head1 Encoding How to ...
703 =item * IO with mixed content (faking iso-2020-*)
705 =item * MIME's Content-Length:
707 =item * UTF-8 strings in binary data.
709 =item * perl/Encode wrappers on non-Unicode XS modules.
713 =head1 Messing with Perl's Internals
715 The following API uses parts of perl's internals in the current implementation.
716 As such they are efficient, but may change.
722 $num_octets = utf8_upgrade($string);
724 Converts internal representation of string to the UTF-8 form.
725 Returns the number of octets necessary to represent the string as UTF-8.
727 =item * utf8_downgrade($string[, CHECK])
729 Converts internal representation of string to be un-encoded bytes.
731 =item * is_utf8(STRING [, CHECK])
733 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
734 If CHECK is true, also checks the data in STRING for being
735 well-formed UTF-8. Returns true if successful, false otherwise.
737 =item * valid_utf8(STRING)
739 [INTERNAL] Test whether STRING is in a consistent state.
740 Will return true if string is held as bytes, or is well-formed UTF-8
741 and has the UTF-8 flag on.
742 Main reason for this routine is to allow perl's testsuite to check
743 that operations have left strings in a consistent state.
749 [INTERNAL] Turn on the UTF-8 flag in STRING. The data in STRING is
750 B<not> checked for being well-formed UTF-8. Do not use unless you
751 B<know> that the STRING is well-formed UTF-8. Returns the previous
752 state of the UTF-8 flag (so please don't test the return value as
753 I<not> success or failure), or C<undef> if STRING is not a string.
759 [INTERNAL] Turn off the UTF-8 flag in STRING. Do not use frivolously.
760 Returns the previous state of the UTF-8 flag (so please don't test the
761 return value as I<not> success or failure), or C<undef> if STRING is
766 =head1 IMPLEMENTATION CLASSES
768 As mentioned above encodings are (in the current implementation at least)
769 defined by objects. The mapping of encoding name to object is via the
772 The values of the hash can currently be either strings or objects.
773 The string form may go away in the future. The string form occurs
774 when C<encodings()> has scanned C<@INC> for loadable encodings but has
775 not actually loaded the encoding in question. This is because the
776 current "loading" process is all perl and a bit slow.
778 Once an encoding is loaded then value of the hash is object which implements
779 the encoding. The object should provide the following interface:
785 Should return the string representing the canonical name of the encoding.
787 =item -E<gt>new_sequence
789 This is a placeholder for encodings with state. It should return an object
790 which implements this interface, all current implementations return the
793 =item -E<gt>encode($string,$check)
795 Should return the octet sequence representing I<$string>. If I<$check> is true
796 it should modify I<$string> in place to remove the converted part (i.e.
797 the whole string unless there is an error).
798 If an error occurs it should return the octet sequence for the
799 fragment of string that has been converted, and modify $string in-place
800 to remove the converted part leaving it starting with the problem fragment.
802 If check is is false then C<encode> should make a "best effort" to convert
803 the string - for example by using a replacement character.
805 =item -E<gt>decode($octets,$check)
807 Should return the string that I<$octets> represents. If I<$check> is true
808 it should modify I<$octets> in place to remove the converted part (i.e.
809 the whole sequence unless there is an error).
810 If an error occurs it should return the fragment of string
811 that has been converted, and modify $octets in-place to remove the converted part
812 leaving it starting with the problem fragment.
814 If check is is false then C<decode> should make a "best effort" to convert
815 the string - for example by using Unicode's "\x{FFFD}" as a replacement character.
819 It should be noted that the check behaviour is different from the outer
820 public API. The logic is that the "unchecked" case is useful when
821 encoding is part of a stream which may be reporting errors (e.g. STDERR).
822 In such cases it is desirable to get everything through somehow without
823 causing additional errors which obscure the original one. Also the encoding
824 is best placed to know what the correct replacement character is, so if that
825 is the desired behaviour then letting low level code do it is the most efficient.
827 In contrast if check is true, the scheme above allows the encoding to do as
828 much as it can and tell layer above how much that was. What is lacking
829 at present is a mechanism to report what went wrong. The most likely interface
830 will be an additional method call to the object, or perhaps
831 (to avoid forcing per-stream objects on otherwise stateless encodings)
832 and additional parameter.
834 It is also highly desirable that encoding classes inherit from C<Encode::Encoding>
835 as a base class. This allows that class to define additional behaviour for
836 all encoding objects. For example built in Unicode, UCS-2 and UTF-8 classes
839 package Encode::MyEncoding;
840 use base qw(Encode::Encoding);
842 __PACKAGE__->Define(qw(myCanonical myAlias));
844 To create an object with bless {Name => ...},$class, and call define_encoding.
845 They inherit their C<name> method from C<Encode::Encoding>.
847 =head2 Compiled Encodings
849 F<Encode.xs> provides a class C<Encode::XS> which provides the interface described
850 above. It calls a generic octet-sequence to octet-sequence "engine" that is
851 driven by tables (defined in F<encengine.c>). The same engine is used for both
852 encode and decode. C<Encode:XS>'s C<encode> forces perl's characters to their UTF-8 form
853 and then treats them as just another multibyte encoding. C<Encode:XS>'s C<decode> transforms
854 the sequence and then turns the UTF-8-ness flag as that is the form that the tables
855 are defined to produce. For details of the engine see the comments in F<encengine.c>.
857 The tables are produced by the perl script F<compile> (the name needs to change so
858 we can eventually install it somewhere). F<compile> can currently read two formats:
864 This is a coined format used by Tcl. It is documented in Encode/EncodeFormat.pod.
868 This is the semi-standard format used by IBM's ICU package.
872 F<compile> can write the following forms:
878 See above - the F<Encode/*.ucm> files provided with the distribution have
879 been created from the original Tcl .enc files using this approach.
883 Produces tables as C data structures - this is used to build in encodings
884 into F<Encode.so>/F<Encode.dll>.
888 In theory this allows encodings to be stand-alone loadable perl extensions.
889 The process has not yet been tested. The plan is to use this approach
890 for large East Asian encodings.
894 The set of encodings built-in to F<Encode.so>/F<Encode.dll> is determined by
895 F<Makefile.PL>. The current set is as follows:
899 =item ascii and iso-8859-*
901 That is all the common 8-bit "western" encodings.
903 =item IBM-1047 and two other variants of EBCDIC.
905 These are the same variants that are supported by EBCDIC perl as "native" encodings.
906 They are included to prove "reversibility" of some constructs in EBCDIC perl.
908 =item symbol and dingbats as used by Tk on X11.
910 (The reason Encode got started was to support perl/Tk.)
914 That set is rather ad. hoc. and has been driven by the needs of the tests rather
915 than the needs of typical applications. It is likely to be rationalized.
919 L<perlunicode>, L<perlebcdic>, L<perlfunc/open>