bdfd686b800342765fd0d6d1063ad04fc1c6d4a8
[p5sagit/p5-mst-13.2.git] / ext / Encode / Encode.pm
1 package Encode;
2 use strict;
3 our $VERSION = do { my @r = (q$Revision: 0.95 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
4
5 require DynaLoader;
6 require Exporter;
7
8 our @ISA = qw(Exporter DynaLoader);
9
10 # Public, encouraged API is exported by default
11 our @EXPORT = qw (
12   encode
13   decode
14   encode_utf8
15   decode_utf8
16   find_encoding
17   encodings
18 );
19
20 our @EXPORT_OK =
21     qw(
22        define_encoding
23        define_alias
24        from_to
25        is_utf8
26        is_8bit
27        is_16bit
28        utf8_upgrade
29        utf8_downgrade
30        _utf8_on
31        _utf8_off
32       );
33
34 bootstrap Encode ();
35
36 # Documentation moved after __END__ for speed - NI-S
37
38 use Carp;
39
40 use Encode::Alias;
41
42 # Make a %encoding package variable to allow a certain amount of cheating
43 our %encoding;
44
45 our %external_tables =
46     (
47         'euc-cn'        => 'Encode/CN.pm',
48         gb2312          => 'Encode/CN.pm',
49         gb12345         => 'Encode/CN.pm',
50         gbk             => 'Encode/CN.pm',
51         cp936           => 'Encode/CN.pm',
52         'iso-ir-165'    => 'Encode/CN.pm',
53         'euc-jp'        => 'Encode/JP.pm',
54         'iso-2022-jp'   => 'Encode/JP.pm',
55         '7bit-jis'      => 'Encode/JP.pm',
56         shiftjis        => 'Encode/JP.pm',
57         macjapan        => 'Encode/JP.pm',
58         cp932           => 'Encode/JP.pm',
59         'euc-kr'        => 'Encode/KR.pm',
60         ksc5601         => 'Encode/KR.pm',
61         cp949           => 'Encode/KR.pm',
62         big5            => 'Encode/TW.pm',
63         'big5-hkscs'    => 'Encode/TW.pm',
64         cp950           => 'Encode/TW.pm',
65         gb18030         => 'Encode/HanExtra.pm',
66         big5plus        => 'Encode/HanExtra.pm',
67         'euc-tw'        => 'Encode/HanExtra.pm',
68     );
69
70 sub encodings
71 {
72  my ($class) = @_;
73  return
74      map { $_->[0] }
75          sort { $a->[1] cmp $b->[1] }
76                map { [$_, lc $_] }
77                    grep { $_ ne 'Internal' }
78                         keys %encoding;
79 }
80
81 sub define_encoding
82 {
83     my $obj  = shift;
84     my $name = shift;
85     $encoding{$name} = $obj;
86     my $lc = lc($name);
87     define_alias($lc => $obj) unless $lc eq $name;
88     while (@_)
89     {
90         my $alias = shift;
91         define_alias($alias,$obj);
92     }
93     return $obj;
94 }
95
96 sub getEncoding
97 {
98     my ($class,$name,$skip_external) = @_;
99     my $enc;
100     if (ref($name) && $name->can('new_sequence'))
101     {
102         return $name;
103     }
104     my $lc = lc $name;
105     if (exists $encoding{$name})
106     {
107         return $encoding{$name};
108     }
109     if (exists $encoding{$lc})
110     {
111         return $encoding{$lc};
112     }
113
114     my $oc = $class->findAlias($name);
115     return $oc if defined $oc;
116
117     $oc = $class->findAlias($lc) if $lc ne $name;
118     return $oc if defined $oc;
119
120     if (!$skip_external and exists $external_tables{$lc})
121     {
122         require $external_tables{$lc};
123         return $encoding{$name} if exists $encoding{$name};
124     }
125
126     return;
127 }
128
129 sub find_encoding
130 {
131     my ($name,$skip_external) = @_;
132     return __PACKAGE__->getEncoding($name,$skip_external);
133 }
134
135 sub encode
136 {
137     my ($name,$string,$check) = @_;
138     my $enc = find_encoding($name);
139     croak("Unknown encoding '$name'") unless defined $enc;
140     my $octets = $enc->encode($string,$check);
141     return undef if ($check && length($string));
142     return $octets;
143 }
144
145 sub decode
146 {
147     my ($name,$octets,$check) = @_;
148     my $enc = find_encoding($name);
149     croak("Unknown encoding '$name'") unless defined $enc;
150     my $string = $enc->decode($octets,$check);
151     $_[1] = $octets if $check;
152     return $string;
153 }
154
155 sub from_to
156 {
157     my ($string,$from,$to,$check) = @_;
158     my $f = find_encoding($from);
159     croak("Unknown encoding '$from'") unless defined $f;
160     my $t = find_encoding($to);
161     croak("Unknown encoding '$to'") unless defined $t;
162     my $uni = $f->decode($string,$check);
163     return undef if ($check && length($string));
164     $string = $t->encode($uni,$check);
165     return undef if ($check && length($uni));
166     return length($_[0] = $string);
167 }
168
169 sub encode_utf8
170 {
171     my ($str) = @_;
172   utf8::encode($str);
173     return $str;
174 }
175
176 sub decode_utf8
177 {
178     my ($str) = @_;
179     return undef unless utf8::decode($str);
180     return $str;
181 }
182
183 require Encode::Encoding;
184 require Encode::XS;
185 require Encode::Internal;
186 require Encode::Unicode;
187 require Encode::utf8;
188 require Encode::iso10646_1;
189 require Encode::ucs2_le;
190
191 1;
192
193 __END__
194
195 =head1 NAME
196
197 Encode - character encodings
198
199 =head1 SYNOPSIS
200
201     use Encode;
202
203 =head1 DESCRIPTION
204
205 The C<Encode> module provides the interfaces between Perl's strings
206 and the rest of the system.  Perl strings are sequences of B<characters>.
207
208 To find more about character encodings, please consult
209 L<Encode::Details> . This document focuses on programming references.
210
211 =head1 PERL ENCODING API
212
213 =head2 Generic Encoding Interface
214
215 =over 4
216
217 =item *
218
219         $bytes  = encode(ENCODING, $string[, CHECK])
220
221 Encodes string from Perl's internal form into I<ENCODING> and returns
222 a sequence of octets.  For CHECK see L</"Handling Malformed Data">.
223
224 For example to convert (internally UTF-8 encoded) Unicode data
225 to octets:
226
227         $octets = encode("utf8", $unicode);
228
229 =item *
230
231         $string = decode(ENCODING, $bytes[, CHECK])
232
233 Decode sequence of octets assumed to be in I<ENCODING> into Perl's
234 internal form and returns the resulting string.  For CHECK see
235 L</"Handling Malformed Data">.
236
237 For example to convert ISO-8859-1 data to UTF-8:
238
239         $utf8 = decode("latin1", $latin1);
240
241 =item *
242
243         from_to($string, FROM_ENCODING, TO_ENCODING[, CHECK])
244
245 Convert B<in-place> the data between two encodings.  How did the data
246 in $string originally get to be in FROM_ENCODING?  Either using
247 encode() or through PerlIO: See L</"Encoding and IO">.  For CHECK
248 see L</"Handling Malformed Data">.
249
250 For example to convert ISO-8859-1 data to UTF-8:
251
252         from_to($data, "iso-8859-1", "utf-8");
253
254 and to convert it back:
255
256         from_to($data, "utf-8", "iso-8859-1");
257
258 Note that because the conversion happens in place, the data to be
259 converted cannot be a string constant, it must be a scalar variable.
260
261 =back
262
263 =head2 Handling Malformed Data
264
265 If CHECK is not set, C<undef> is returned.  If the data is supposed to
266 be UTF-8, an optional lexical warning (category utf8) is given.  If
267 CHECK is true but not a code reference, dies.
268
269 It would desirable to have a way to indicate that transform should use
270 the encodings "replacement character" - no such mechanism is defined yet.
271
272 It is also planned to allow I<CHECK> to be a code reference.
273
274 This is not yet implemented as there are design issues with what its
275 arguments should be and how it returns its results.
276
277 =over 4
278
279 =item Scheme 1
280
281 Passed remaining fragment of string being processed.
282 Modifies it in place to remove bytes/characters it can understand
283 and returns a string used to represent them.
284 e.g.
285
286  sub fixup {
287    my $ch = substr($_[0],0,1,'');
288    return sprintf("\x{%02X}",ord($ch);
289  }
290
291 This scheme is close to how underlying C code for Encode works, but gives
292 the fixup routine very little context.
293
294 =item Scheme 2
295
296 Passed original string, and an index into it of the problem area, and
297 output string so far.  Appends what it will to output string and
298 returns new index into original string.  For example:
299
300  sub fixup {
301    # my ($s,$i,$d) = @_;
302    my $ch = substr($_[0],$_[1],1);
303    $_[2] .= sprintf("\x{%02X}",ord($ch);
304    return $_[1]+1;
305  }
306
307 This scheme gives maximal control to the fixup routine but is more
308 complicated to code, and may need internals of Encode to be tweaked to
309 keep original string intact.
310
311 =item Other Schemes
312
313 Hybrids of above.
314
315 Multiple return values rather than in-place modifications.
316
317 Index into the string could be pos($str) allowing s/\G...//.
318
319 =back
320
321 =head2 UTF-8 / utf8
322
323 The Unicode consortium defines the UTF-8 standard as a way of encoding
324 the entire Unicode repertiore as sequences of octets.  This encoding is
325 expected to become very widespread. Perl can use this form internaly
326 to represent strings, so conversions to and from this form are
327 particularly efficient (as octets in memory do not have to change,
328 just the meta-data that tells Perl how to treat them).
329
330 =over 4
331
332 =item *
333
334         $bytes = encode_utf8($string);
335
336 The characters that comprise string are encoded in Perl's superset of UTF-8
337 and the resulting octets returned as a sequence of bytes. All possible
338 characters have a UTF-8 representation so this function cannot fail.
339
340 =item *
341
342         $string = decode_utf8($bytes [,CHECK]);
343
344 The sequence of octets represented by $bytes is decoded from UTF-8
345 into a sequence of logical characters. Not all sequences of octets
346 form valid UTF-8 encodings, so it is possible for this call to fail.
347 For CHECK see L</"Handling Malformed Data">.
348
349 =back
350
351 =head2 Listing available encodings
352
353   use Encode qw(encodings);
354   @list = encodings();
355
356 Returns a list of the canonical names of the available encodings. 
357
358 To find which encodings are suppoted by this package in details, 
359 see L<Encode::Supported>.
360
361 =head2 Defining Aliases
362
363   use Encode qw(define_alias);
364   define_alias( newName => ENCODING);
365
366 Allows newName to be used as am alias for ENCODING. ENCODING may be
367 either the name of an encoding or and encoding object (as above).
368
369 See L<Encode::Alias> on details.
370
371 =head1 Defining Encodings
372
373     use Encode qw(define_alias);
374     define_encoding( $object, 'canonicalName' [,alias...]);
375
376 Causes I<canonicalName> to be associated with I<$object>.  The object
377 should provide the interface described in L<Encode::Encoding>
378 below.  If more than two arguments are provided then additional
379 arguments are taken as aliases for I<$object> as for C<define_alias>.
380
381 =head1 Encoding and IO
382
383 It is very common to want to do encoding transformations when
384 reading or writing files, network connections, pipes etc.
385 If Perl is configured to use the new 'perlio' IO system then
386 C<Encode> provides a "layer" (See L<perliol>) which can transform
387 data as it is read or written.
388
389 Here is how the blind poet would modernise the encoding:
390
391     use Encode;
392     open(my $iliad,'<:encoding(iso-8859-7)','iliad.greek');
393     open(my $utf8,'>:utf8','iliad.utf8');
394     my @epic = <$iliad>;
395     print $utf8 @epic;
396     close($utf8);
397     close($illiad);
398
399 In addition the new IO system can also be configured to read/write
400 UTF-8 encoded characters (as noted above this is efficient):
401
402     open(my $fh,'>:utf8','anything');
403     print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
404
405 Either of the above forms of "layer" specifications can be made the default
406 for a lexical scope with the C<use open ...> pragma. See L<open>.
407
408 Once a handle is open is layers can be altered using C<binmode>.
409
410 Without any such configuration, or if Perl itself is built using
411 system's own IO, then write operations assume that file handle accepts
412 only I<bytes> and will C<die> if a character larger than 255 is
413 written to the handle. When reading, each octet from the handle
414 becomes a byte-in-a-character. Note that this default is the same
415 behaviour as bytes-only languages (including Perl before v5.6) would
416 have, and is sufficient to handle native 8-bit encodings
417 e.g. iso-8859-1, EBCDIC etc. and any legacy mechanisms for handling
418 other encodings and binary data.
419
420 In other cases it is the programs responsibility to transform
421 characters into bytes using the API above before doing writes, and to
422 transform the bytes read from a handle into characters before doing
423 "character operations" (e.g. C<lc>, C</\W+/>, ...).
424
425 You can also use PerlIO to convert larger amounts of data you don't
426 want to bring into memory.  For example to convert between ISO-8859-1
427 (Latin 1) and UTF-8 (or UTF-EBCDIC in EBCDIC machines):
428
429     open(F, "<:encoding(iso-8859-1)", "data.txt") or die $!;
430     open(G, ">:utf8",                 "data.utf") or die $!;
431     while (<F>) { print G }
432
433     # Could also do "print G <F>" but that would pull
434     # the whole file into memory just to write it out again.
435
436 More examples:
437
438     open(my $f, "<:encoding(cp1252)")
439     open(my $g, ">:encoding(iso-8859-2)")
440     open(my $h, ">:encoding(latin9)")       # iso-8859-15
441
442 See L<PerlIO> for more information.
443
444 See also L<encoding> for how to change the default encoding of the
445 data in your script.
446
447 =head1 Messing with Perl's Internals
448
449 The following API uses parts of Perl's internals in the current
450 implementation.  As such they are efficient, but may change.
451
452 =over 4
453
454 =item * is_utf8(STRING [, CHECK])
455
456 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
457 If CHECK is true, also checks the data in STRING for being well-formed
458 UTF-8.  Returns true if successful, false otherwise.
459
460 =item *
461
462         _utf8_on(STRING)
463
464 [INTERNAL] Turn on the UTF-8 flag in STRING.  The data in STRING is
465 B<not> checked for being well-formed UTF-8.  Do not use unless you
466 B<know> that the STRING is well-formed UTF-8.  Returns the previous
467 state of the UTF-8 flag (so please don't test the return value as
468 I<not> success or failure), or C<undef> if STRING is not a string.
469
470 =item *
471
472         _utf8_off(STRING)
473
474 [INTERNAL] Turn off the UTF-8 flag in STRING.  Do not use frivolously.
475 Returns the previous state of the UTF-8 flag (so please don't test the
476 return value as I<not> success or failure), or C<undef> if STRING is
477 not a string.
478
479 =back
480
481 =head1 SEE ALSO
482
483 L<Encode::Details>, 
484 L<Encode::Encoding>,
485 L<Encode::Supported>,
486 L<PerlIO>, 
487 L<encoding>,
488 L<perlebcdic>, 
489 L<perlfunc/open>, 
490 L<perlunicode>, 
491 L<utf8>, 
492 the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>
493
494 =cut