3 our $VERSION = do { my @r = (q$Revision: 1.40 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
9 our @ISA = qw(Exporter DynaLoader);
11 # Public, encouraged API is exported by default
37 # Documentation moved after __END__ for speed - NI-S
41 our $ON_EBCDIC = (ord("A") == 193);
45 # Make a %Encoding package variable to allow a certain amount of cheating
48 require Encode::Config;
49 eval { require Encode::ConfigLocal };
54 my @modules = (@_ and $_[0] eq ":all") ? values %ExtModule : @_;
55 for my $mod (@modules){
56 $mod =~ s,::,/,g or $mod = "Encode/$mod";
58 $DEBUG and warn "about to require $mod;";
59 eval { require $mod; };
61 my %modules = map {$_ => 1} @modules;
63 sort { lc $a cmp lc $b }
64 grep {!/^(?:Internal|Unicode)$/o} keys %Encoding;
71 $Encoding{$name} = $obj;
73 define_alias($lc => $obj) unless $lc eq $name;
77 define_alias($alias,$obj);
84 my ($class,$name,$skip_external) = @_;
86 if (ref($name) && $name->can('new_sequence'))
91 if (exists $Encoding{$name})
93 return $Encoding{$name};
95 if (exists $Encoding{$lc})
97 return $Encoding{$lc};
100 my $oc = $class->find_alias($name);
101 return $oc if defined $oc;
103 $oc = $class->find_alias($lc) if $lc ne $name;
104 return $oc if defined $oc;
106 unless ($skip_external)
108 if (my $mod = $ExtModule{$name} || $ExtModule{$lc}){
109 $mod =~ s,::,/,g ; $mod .= '.pm';
110 eval{ require $mod; };
111 return $Encoding{$name} if exists $Encoding{$name};
119 my ($name,$skip_external) = @_;
120 return __PACKAGE__->getEncoding($name,$skip_external);
124 my $obj = find_encoding(shift);
125 defined $obj and return $obj->name;
131 my ($name,$string,$check) = @_;
132 my $enc = find_encoding($name);
133 croak("Unknown encoding '$name'") unless defined $enc;
134 my $octets = $enc->encode($string,$check);
135 return undef if ($check && length($string));
141 my ($name,$octets,$check) = @_;
142 my $enc = find_encoding($name);
143 croak("Unknown encoding '$name'") unless defined $enc;
144 my $string = $enc->decode($octets,$check);
145 $_[1] = $octets if $check;
151 my ($string,$from,$to,$check) = @_;
152 my $f = find_encoding($from);
153 croak("Unknown encoding '$from'") unless defined $f;
154 my $t = find_encoding($to);
155 croak("Unknown encoding '$to'") unless defined $t;
156 my $uni = $f->decode($string,$check);
157 return undef if ($check && length($string));
158 $string = $t->encode($uni,$check);
159 return undef if ($check && length($uni));
160 return defined($_[0] = $string) ? length($string) : undef ;
173 return undef unless utf8::decode($str);
177 predefine_encodings();
180 # This is to restore %Encoding if really needed;
182 sub predefine_encodings{
184 # was in Encode::UTF_EBCDIC
185 package Encode::UTF_EBCDIC;
186 *name = sub{ shift->{'Name'} };
187 *new_sequence = sub{ return $_[0] };
189 my ($obj,$str,$chk) = @_;
191 for (my $i = 0; $i < length($str); $i++) {
193 chr(utf8::unicode_to_native(ord(substr($str,$i,1))));
199 my ($obj,$str,$chk) = @_;
201 for (my $i = 0; $i < length($str); $i++) {
203 chr(utf8::native_to_unicode(ord(substr($str,$i,1))));
208 $Encode::Encoding{Unicode} =
209 bless {Name => "UTF_EBCDIC"} => "Encode::UTF_EBCDIC";
211 # was in Encode::UTF_EBCDIC
212 package Encode::Internal;
213 *name = sub{ shift->{'Name'} };
214 *new_sequence = sub{ return $_[0] };
216 my ($obj,$str,$chk) = @_;
222 $Encode::Encoding{Unicode} =
223 bless {Name => "Internal"} => "Encode::Internal";
227 # was in Encode::utf8
228 package Encode::utf8;
229 *name = sub{ shift->{'Name'} };
230 *new_sequence = sub{ return $_[0] };
232 my ($obj,$octets,$chk) = @_;
233 my $str = Encode::decode_utf8($octets);
241 my ($obj,$string,$chk) = @_;
242 my $octets = Encode::encode_utf8($string);
246 $Encode::Encoding{utf8} =
247 bless {Name => "utf8"} => "Encode::utf8";
251 require Encode::Encoding;
260 Encode - character encodings
267 =head2 Table of Contents
269 Encode consists of a collection of modules which details are too big
270 to fit in one document. This POD itself explains the top-level APIs
271 and general topics at a glance. For other topics and more details,
275 --------------------------------------------------------
276 Encode::Alias Alias defintions to encodings
277 Encode::Encoding Encode Implementation Base Class
278 Encode::Supported List of Supported Encodings
279 Encode::CN Simplified Chinese Encodings
280 Encode::JP Japanese Encodings
281 Encode::KR Korean Encodings
282 Encode::TW Traditional Chinese Encodings
283 --------------------------------------------------------
287 The C<Encode> module provides the interfaces between Perl's strings
288 and the rest of the system. Perl strings are sequences of
291 The repertoire of characters that Perl can represent is at least that
292 defined by the Unicode Consortium. On most platforms the ordinal
293 values of the characters (as returned by C<ord(ch)>) is the "Unicode
294 codepoint" for the character (the exceptions are those platforms where
295 the legacy encoding is some variant of EBCDIC rather than a super-set
296 of ASCII - see L<perlebcdic>).
298 Traditionally computer data has been moved around in 8-bit chunks
299 often called "bytes". These chunks are also known as "octets" in
300 networking standards. Perl is widely used to manipulate data of many
301 types - not only strings of characters representing human or computer
302 languages but also "binary" data being the machines representation of
303 numbers, pixels in an image - or just about anything.
305 When Perl is processing "binary data" the programmer wants Perl to
306 process "sequences of bytes". This is not a problem for Perl - as a
307 byte has 256 possible values it easily fits in Perl's much larger
316 I<character>: a character in the range 0..(2**32-1) (or more).
317 (What Perl's strings are made of.)
321 I<byte>: a character in the range 0..255
322 (A special case of a Perl character.)
326 I<octet>: 8 bits of data, with ordinal values 0..255
327 (Term for bytes passed to or from a non-Perl context, e.g. disk file.)
331 The marker [INTERNAL] marks Internal Implementation Details, in
332 general meant only for those who think they know what they are doing,
333 and such details may change in future releases.
335 =head1 PERL ENCODING API
339 =item $octets = encode(ENCODING, $string[, CHECK])
341 Encodes string from Perl's internal form into I<ENCODING> and returns
342 a sequence of octets. ENCODING can be either a canonical name or
343 alias. For encoding names and aliases, see L</"Defining Aliases">.
344 For CHECK see L</"Handling Malformed Data">.
346 For example to convert (internally UTF-8 encoded) Unicode string to
347 iso-8859-1 (also known as Latin1),
349 $octets = encode("iso-8859-1", $unicode);
351 =item $string = decode(ENCODING, $octets[, CHECK])
353 Decode sequence of octets assumed to be in I<ENCODING> into Perl's
354 internal form and returns the resulting string. as in encode(),
355 ENCODING can be either a canonical name or alias. For encoding names
356 and aliases, see L</"Defining Aliases">. For CHECK see
357 L</"Handling Malformed Data">.
359 For example to convert ISO-8859-1 data to UTF-8:
361 $utf8 = decode("iso-8859-1", $latin1);
363 =item [$length =] from_to($string, FROM_ENCODING, TO_ENCODING [,CHECK])
365 Convert B<in-place> the data between two encodings. How did the data
366 in $string originally get to be in FROM_ENCODING? Either using
367 encode() or through PerlIO: See L</"Encoding and IO">.
368 For encoding names and aliases, see L</"Defining Aliases">.
369 For CHECK see L</"Handling Malformed Data">.
371 For example to convert ISO-8859-1 data to UTF-8:
373 from_to($data, "iso-8859-1", "utf-8");
375 and to convert it back:
377 from_to($data, "utf-8", "iso-8859-1");
379 Note that because the conversion happens in place, the data to be
380 converted cannot be a string constant, it must be a scalar variable.
382 from_to() return the length of the converted string on success, undef
389 The Unicode consortium defines the UTF-8 standard as a way of encoding
390 the entire Unicode repertoire as sequences of octets. This encoding is
391 expected to become very widespread. Perl can use this form internally
392 to represent strings, so conversions to and from this form are
393 particularly efficient (as octets in memory do not have to change,
394 just the meta-data that tells Perl how to treat them).
398 =item $octets = encode_utf8($string);
400 The characters that comprise string are encoded in Perl's superset of UTF-8
401 and the resulting octets returned as a sequence of bytes. All possible
402 characters have a UTF-8 representation so this function cannot fail.
404 =item $string = decode_utf8($octets [, CHECK]);
406 The sequence of octets represented by $octets is decoded from UTF-8
407 into a sequence of logical characters. Not all sequences of octets
408 form valid UTF-8 encodings, so it is possible for this call to fail.
409 For CHECK see L</"Handling Malformed Data">.
413 =head2 Listing available encodings
416 @list = Encode->encodings();
418 Returns a list of the canonical names of the available encodings that
419 are loaded. To get a list of all available encodings including the
420 ones that are not loaded yet, say
422 @all_encodings = Encode->encodings(":all");
424 Or you can give the name of specific module.
426 @with_jp = Encode->encodings("Encode::JP");
428 When "::" is not in the name, "Encode::" is assumed.
430 @ebcdic = Encode->encodings("EBCDIC");
432 To find which encodings are supported by this package in details,
433 see L<Encode::Supported>.
435 =head2 Defining Aliases
437 To add new alias to a given encoding, Use;
441 define_alias(newName => ENCODING);
443 After that, newName can be used as an alias for ENCODING.
444 ENCODING may be either the name of an encoding or an
447 But before you do so, make sure the alias is nonexistent with
448 C<resolve_alias()>, which returns the canonical name thereof.
451 Encode::resolve_alias("latin1") eq "iso-8859-1" # true
452 Encode::resolve_alias("iso-8859-12") # false; nonexistent
453 Encode::resolve_alias($name) eq $name # true if $name is canonical
455 This resolve_alias() does not need C<use Encode::Alias> and is
456 exported via C<use encode qw(resolve_alias)>.
458 See L<Encode::Alias> on details.
460 =head1 Encoding and IO
462 It is very common to want to do encoding transformations when
463 reading or writing files, network connections, pipes etc.
464 If Perl is configured to use the new 'perlio' IO system then
465 C<Encode> provides a "layer" (See L<perliol>) which can transform
466 data as it is read or written.
468 Here is how the blind poet would modernise the encoding:
471 open(my $iliad,'<:encoding(iso-8859-7)','iliad.greek');
472 open(my $utf8,'>:utf8','iliad.utf8');
478 In addition the new IO system can also be configured to read/write
479 UTF-8 encoded characters (as noted above this is efficient):
481 open(my $fh,'>:utf8','anything');
482 print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
484 Either of the above forms of "layer" specifications can be made the default
485 for a lexical scope with the C<use open ...> pragma. See L<open>.
487 Once a handle is open is layers can be altered using C<binmode>.
489 Without any such configuration, or if Perl itself is built using
490 system's own IO, then write operations assume that file handle accepts
491 only I<bytes> and will C<die> if a character larger than 255 is
492 written to the handle. When reading, each octet from the handle
493 becomes a byte-in-a-character. Note that this default is the same
494 behaviour as bytes-only languages (including Perl before v5.6) would
495 have, and is sufficient to handle native 8-bit encodings
496 e.g. iso-8859-1, EBCDIC etc. and any legacy mechanisms for handling
497 other encodings and binary data.
499 In other cases it is the programs responsibility to transform
500 characters into bytes using the API above before doing writes, and to
501 transform the bytes read from a handle into characters before doing
502 "character operations" (e.g. C<lc>, C</\W+/>, ...).
504 You can also use PerlIO to convert larger amounts of data you don't
505 want to bring into memory. For example to convert between ISO-8859-1
506 (Latin 1) and UTF-8 (or UTF-EBCDIC in EBCDIC machines):
508 open(F, "<:encoding(iso-8859-1)", "data.txt") or die $!;
509 open(G, ">:utf8", "data.utf") or die $!;
510 while (<F>) { print G }
512 # Could also do "print G <F>" but that would pull
513 # the whole file into memory just to write it out again.
517 open(my $f, "<:encoding(cp1252)")
518 open(my $g, ">:encoding(iso-8859-2)")
519 open(my $h, ">:encoding(latin9)") # iso-8859-15
521 See L<PerlIO> for more information.
523 See also L<encoding> for how to change the default encoding of the
526 =head1 Handling Malformed Data
528 If I<CHECK> is not set, (en|de)code will put I<substitution character> in
529 place of the malformed character. for UCM-based encodings,
530 E<lt>subcharE<gt> will be used. For Unicode, \xFFFD is used. If the
531 data is supposed to be UTF-8, an optional lexical warning (category
534 If I<CHECK> is true but not a code reference, dies with an error message.
536 In future you will be able to use a code reference to a callback
537 function for the value of I<CHECK> but its API is still undecided.
539 =head1 Defining Encodings
541 To define a new encoding, use:
543 use Encode qw(define_alias);
544 define_encoding($object, 'canonicalName' [, alias...]);
546 I<canonicalName> will be associated with I<$object>. The object
547 should provide the interface described in L<Encode::Encoding>
548 If more than two arguments are provided then additional
549 arguments are taken as aliases for I<$object> as for C<define_alias>.
551 See L<Encode::Encoding> for more details.
553 =head1 Messing with Perl's Internals
555 The following API uses parts of Perl's internals in the current
556 implementation. As such they are efficient, but may change.
560 =item is_utf8(STRING [, CHECK])
562 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
563 If CHECK is true, also checks the data in STRING for being well-formed
564 UTF-8. Returns true if successful, false otherwise.
566 =item _utf8_on(STRING)
568 [INTERNAL] Turn on the UTF-8 flag in STRING. The data in STRING is
569 B<not> checked for being well-formed UTF-8. Do not use unless you
570 B<know> that the STRING is well-formed UTF-8. Returns the previous
571 state of the UTF-8 flag (so please don't test the return value as
572 I<not> success or failure), or C<undef> if STRING is not a string.
574 =item _utf8_off(STRING)
576 [INTERNAL] Turn off the UTF-8 flag in STRING. Do not use frivolously.
577 Returns the previous state of the UTF-8 flag (so please don't test the
578 return value as I<not> success or failure), or C<undef> if STRING is
586 L<Encode::Supported>,
593 the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>
597 This project was originated by Nick Ing-Simmons and later maintained
598 by Dan Kogai E<lt>dankogai@dan.co.jpE<gt>. See AUTHORS for full list
599 of people involved. For any questions, use
600 E<lt>perl-unicode@perl.orgE<gt> so others can share.