3 our $VERSION = do { my @r = (q$Revision: 1.32 $ =~ /\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
52 my @modules = (@_ and $_[0] eq ":all") ? values %ExtModule : @_;
53 for my $mod (@modules){
54 $mod =~ s,::,/,g or $mod = "Encode/$mod";
56 $DEBUG and warn "about to require $mod;";
57 eval { require $mod; };
59 my %modules = map {$_ => 1} @modules;
61 sort { lc $a cmp lc $b }
62 grep {!/^(?:Internal|Unicode)$/o} keys %Encoding;
69 $Encoding{$name} = $obj;
71 define_alias($lc => $obj) unless $lc eq $name;
75 define_alias($alias,$obj);
82 my ($class,$name,$skip_external) = @_;
84 if (ref($name) && $name->can('new_sequence'))
89 if (exists $Encoding{$name})
91 return $Encoding{$name};
93 if (exists $Encoding{$lc})
95 return $Encoding{$lc};
98 my $oc = $class->find_alias($name);
99 return $oc if defined $oc;
101 $oc = $class->find_alias($lc) if $lc ne $name;
102 return $oc if defined $oc;
104 unless ($skip_external)
106 if (my $mod = $ExtModule{$name} || $ExtModule{$lc}){
107 $mod =~ s,::,/,g ; $mod .= '.pm';
108 eval{ require $mod; };
109 return $Encoding{$name} if exists $Encoding{$name};
117 my ($name,$skip_external) = @_;
118 return __PACKAGE__->getEncoding($name,$skip_external);
122 my $obj = find_encoding(shift);
123 defined $obj and return $obj->name;
129 my ($name,$string,$check) = @_;
130 my $enc = find_encoding($name);
131 croak("Unknown encoding '$name'") unless defined $enc;
132 my $octets = $enc->encode($string,$check);
133 return undef if ($check && length($string));
139 my ($name,$octets,$check) = @_;
140 my $enc = find_encoding($name);
141 croak("Unknown encoding '$name'") unless defined $enc;
142 my $string = $enc->decode($octets,$check);
143 $_[1] = $octets if $check;
149 my ($string,$from,$to,$check) = @_;
150 my $f = find_encoding($from);
151 croak("Unknown encoding '$from'") unless defined $f;
152 my $t = find_encoding($to);
153 croak("Unknown encoding '$to'") unless defined $t;
154 my $uni = $f->decode($string,$check);
155 return undef if ($check && length($string));
156 $string = $t->encode($uni,$check);
157 return undef if ($check && length($uni));
158 return defined($_[0] = $string) ? length($string) : undef ;
171 return undef unless utf8::decode($str);
175 predefine_encodings();
178 # This is to restore %Encoding if really needed;
180 sub predefine_encodings{
182 # was in Encode::UTF_EBCDIC
183 package Encode::UTF_EBCDIC;
184 *name = sub{ shift->{'Name'} };
185 *new_sequence = sub{ return $_[0] };
187 my ($obj,$str,$chk) = @_;
189 for (my $i = 0; $i < length($str); $i++) {
191 chr(utf8::unicode_to_native(ord(substr($str,$i,1))));
197 my ($obj,$str,$chk) = @_;
199 for (my $i = 0; $i < length($str); $i++) {
201 chr(utf8::native_to_unicode(ord(substr($str,$i,1))));
206 $Encode::Encoding{Internal} =
207 bless {Name => "UTF_EBCDIC"} => "Encode::UTF_EBCDIC";
209 # was in Encode::UTF_EBCDIC
210 package Encode::Internal;
211 *name = sub{ shift->{'Name'} };
212 *new_sequence = sub{ return $_[0] };
214 my ($obj,$str,$chk) = @_;
220 $Encode::Encoding{Unicode} =
221 bless {Name => "Internal"} => "Encode::Internal";
225 # was in Encode::utf8
226 package Encode::utf8;
227 *name = sub{ shift->{'Name'} };
228 *new_sequence = sub{ return $_[0] };
230 my ($obj,$octets,$chk) = @_;
231 my $str = Encode::decode_utf8($octets);
239 my ($obj,$string,$chk) = @_;
240 my $octets = Encode::encode_utf8($string);
244 $Encode::Encoding{utf8} =
245 bless {Name => "utf8"} => "Encode::utf8";
247 # do externals if necessary
248 require File::Basename;
252 File::Spec->catfile(File::Basename::dirname($INC{'Encode.pm'}),
253 "Encode", "$ext.pm");
258 require Encode::Encoding;
267 Encode - character encodings
274 =head2 Table of Contents
276 Encode consists of a collection of modules which details are too big
277 to fit in one document. This POD itself explains the top-level APIs
278 and general topics at a glance. For other topics and more details,
282 --------------------------------------------------------
283 Encode::Alias Alias defintions to encodings
284 Encode::Encoding Encode Implementation Base Class
285 Encode::Supported List of Supported Encodings
286 Encode::CN Simplified Chinese Encodings
287 Encode::JP Japanese Encodings
288 Encode::KR Korean Encodings
289 Encode::TW Traditional Chinese Encodings
290 --------------------------------------------------------
294 The C<Encode> module provides the interfaces between Perl's strings
295 and the rest of the system. Perl strings are sequences of
298 The repertoire of characters that Perl can represent is at least that
299 defined by the Unicode Consortium. On most platforms the ordinal
300 values of the characters (as returned by C<ord(ch)>) is the "Unicode
301 codepoint" for the character (the exceptions are those platforms where
302 the legacy encoding is some variant of EBCDIC rather than a super-set
303 of ASCII - see L<perlebcdic>).
305 Traditionally computer data has been moved around in 8-bit chunks
306 often called "bytes". These chunks are also known as "octets" in
307 networking standards. Perl is widely used to manipulate data of many
308 types - not only strings of characters representing human or computer
309 languages but also "binary" data being the machines representation of
310 numbers, pixels in an image - or just about anything.
312 When Perl is processing "binary data" the programmer wants Perl to
313 process "sequences of bytes". This is not a problem for Perl - as a
314 byte has 256 possible values it easily fits in Perl's much larger
323 I<character>: a character in the range 0..(2**32-1) (or more).
324 (What Perl's strings are made of.)
328 I<byte>: a character in the range 0..255
329 (A special case of a Perl character.)
333 I<octet>: 8 bits of data, with ordinal values 0..255
334 (Term for bytes passed to or from a non-Perl context, e.g. disk file.)
338 The marker [INTERNAL] marks Internal Implementation Details, in
339 general meant only for those who think they know what they are doing,
340 and such details may change in future releases.
342 =head1 PERL ENCODING API
346 =item $octets = encode(ENCODING, $string[, CHECK])
348 Encodes string from Perl's internal form into I<ENCODING> and returns
349 a sequence of octets. ENCODING can be either a canonical name or
350 alias. For encoding names and aliases, see L</"Defining Aliases">.
351 For CHECK see L</"Handling Malformed Data">.
353 For example to convert (internally UTF-8 encoded) Unicode string to
354 iso-8859-1 (also known as Latin1),
356 $octets = encode("iso-8859-1", $unicode);
358 =item $string = decode(ENCODING, $octets[, CHECK])
360 Decode sequence of octets assumed to be in I<ENCODING> into Perl's
361 internal form and returns the resulting string. as in encode(),
362 ENCODING can be either a canonical name or alias. For encoding names
363 and aliases, see L</"Defining Aliases">. For CHECK see
364 L</"Handling Malformed Data">.
366 For example to convert ISO-8859-1 data to UTF-8:
368 $utf8 = decode("iso-8859-1", $latin1);
370 =item [$length =] from_to($string, FROM_ENCODING, TO_ENCODING [,CHECK])
372 Convert B<in-place> the data between two encodings. How did the data
373 in $string originally get to be in FROM_ENCODING? Either using
374 encode() or through PerlIO: See L</"Encoding and IO">.
375 For encoding names and aliases, see L</"Defining Aliases">.
376 For CHECK see L</"Handling Malformed Data">.
378 For example to convert ISO-8859-1 data to UTF-8:
380 from_to($data, "iso-8859-1", "utf-8");
382 and to convert it back:
384 from_to($data, "utf-8", "iso-8859-1");
386 Note that because the conversion happens in place, the data to be
387 converted cannot be a string constant, it must be a scalar variable.
389 from_to() return the length of the converted string on success, undef
396 The Unicode consortium defines the UTF-8 standard as a way of encoding
397 the entire Unicode repertoire as sequences of octets. This encoding is
398 expected to become very widespread. Perl can use this form internally
399 to represent strings, so conversions to and from this form are
400 particularly efficient (as octets in memory do not have to change,
401 just the meta-data that tells Perl how to treat them).
405 =item $octets = encode_utf8($string);
407 The characters that comprise string are encoded in Perl's superset of UTF-8
408 and the resulting octets returned as a sequence of bytes. All possible
409 characters have a UTF-8 representation so this function cannot fail.
411 =item $string = decode_utf8($octets [, CHECK]);
413 The sequence of octets represented by $octets is decoded from UTF-8
414 into a sequence of logical characters. Not all sequences of octets
415 form valid UTF-8 encodings, so it is possible for this call to fail.
416 For CHECK see L</"Handling Malformed Data">.
420 =head2 Listing available encodings
423 @list = Encode->encodings();
425 Returns a list of the canonical names of the available encodings that
426 are loaded. To get a list of all available encodings including the
427 ones that are not loaded yet, say
429 @all_encodings = Encode->encodings(":all");
431 Or you can give the name of specific module.
433 @with_jp = Encode->encodings("Encode::JP");
435 When "::" is not in the name, "Encode::" is assumed.
437 @ebcdic = Encode->encodings("EBCDIC");
439 To find which encodings are supported by this package in details,
440 see L<Encode::Supported>.
442 =head2 Defining Aliases
444 To add new alias to a given encoding, Use;
448 define_alias(newName => ENCODING);
450 After that, newName can be used as an alias for ENCODING.
451 ENCODING may be either the name of an encoding or an
454 But before you do so, make sure the alias is nonexistent with
455 C<resolve_alias()>, which returns the canonical name thereof.
458 Encode::resolve_alias("latin1") eq "iso-8859-1" # true
459 Encode::resolve_alias("iso-8859-12") # false; nonexistent
460 Encode::resolve_alias($name) eq $name # true if $name is canonical
462 This resolve_alias() does not need C<use Encode::Alias> and is
463 exported via C<use encode qw(resolve_alias)>.
465 See L<Encode::Alias> on details.
467 =head1 Encoding and IO
469 It is very common to want to do encoding transformations when
470 reading or writing files, network connections, pipes etc.
471 If Perl is configured to use the new 'perlio' IO system then
472 C<Encode> provides a "layer" (See L<perliol>) which can transform
473 data as it is read or written.
475 Here is how the blind poet would modernise the encoding:
478 open(my $iliad,'<:encoding(iso-8859-7)','iliad.greek');
479 open(my $utf8,'>:utf8','iliad.utf8');
485 In addition the new IO system can also be configured to read/write
486 UTF-8 encoded characters (as noted above this is efficient):
488 open(my $fh,'>:utf8','anything');
489 print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
491 Either of the above forms of "layer" specifications can be made the default
492 for a lexical scope with the C<use open ...> pragma. See L<open>.
494 Once a handle is open is layers can be altered using C<binmode>.
496 Without any such configuration, or if Perl itself is built using
497 system's own IO, then write operations assume that file handle accepts
498 only I<bytes> and will C<die> if a character larger than 255 is
499 written to the handle. When reading, each octet from the handle
500 becomes a byte-in-a-character. Note that this default is the same
501 behaviour as bytes-only languages (including Perl before v5.6) would
502 have, and is sufficient to handle native 8-bit encodings
503 e.g. iso-8859-1, EBCDIC etc. and any legacy mechanisms for handling
504 other encodings and binary data.
506 In other cases it is the programs responsibility to transform
507 characters into bytes using the API above before doing writes, and to
508 transform the bytes read from a handle into characters before doing
509 "character operations" (e.g. C<lc>, C</\W+/>, ...).
511 You can also use PerlIO to convert larger amounts of data you don't
512 want to bring into memory. For example to convert between ISO-8859-1
513 (Latin 1) and UTF-8 (or UTF-EBCDIC in EBCDIC machines):
515 open(F, "<:encoding(iso-8859-1)", "data.txt") or die $!;
516 open(G, ">:utf8", "data.utf") or die $!;
517 while (<F>) { print G }
519 # Could also do "print G <F>" but that would pull
520 # the whole file into memory just to write it out again.
524 open(my $f, "<:encoding(cp1252)")
525 open(my $g, ">:encoding(iso-8859-2)")
526 open(my $h, ">:encoding(latin9)") # iso-8859-15
528 See L<PerlIO> for more information.
530 See also L<encoding> for how to change the default encoding of the
533 =head1 Handling Malformed Data
535 If I<CHECK> is not set, (en|de)code will put I<substitution character> in
536 place of the malformed character. for UCM-based encodings,
537 E<lt>subcharE<gt> will be used. For Unicode, \xFFFD is used. If the
538 data is supposed to be UTF-8, an optional lexical warning (category
541 If I<CHECK> is true but not a code reference, dies with an error message.
543 In future you will be able to use a code reference to a callback
544 function for the value of I<CHECK> but its API is still undecided.
546 =head1 Defining Encodings
548 To define a new encoding, use:
550 use Encode qw(define_alias);
551 define_encoding($object, 'canonicalName' [, alias...]);
553 I<canonicalName> will be associated with I<$object>. The object
554 should provide the interface described in L<Encode::Encoding>
555 If more than two arguments are provided then additional
556 arguments are taken as aliases for I<$object> as for C<define_alias>.
558 See L<Encode::Encoding> for more details.
560 =head1 Messing with Perl's Internals
562 The following API uses parts of Perl's internals in the current
563 implementation. As such they are efficient, but may change.
567 =item is_utf8(STRING [, CHECK])
569 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
570 If CHECK is true, also checks the data in STRING for being well-formed
571 UTF-8. Returns true if successful, false otherwise.
573 =item _utf8_on(STRING)
575 [INTERNAL] Turn on the UTF-8 flag in STRING. The data in STRING is
576 B<not> checked for being well-formed UTF-8. Do not use unless you
577 B<know> that the STRING is well-formed UTF-8. Returns the previous
578 state of the UTF-8 flag (so please don't test the return value as
579 I<not> success or failure), or C<undef> if STRING is not a string.
581 =item _utf8_off(STRING)
583 [INTERNAL] Turn off the UTF-8 flag in STRING. Do not use frivolously.
584 Returns the previous state of the UTF-8 flag (so please don't test the
585 return value as I<not> success or failure), or C<undef> if STRING is
593 L<Encode::Supported>,
600 the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>