Commit | Line | Data |
2c674647 |
1 | package Encode; |
51ef4e11 |
2 | use strict; |
2c674647 |
3 | |
51ef4e11 |
4 | our $VERSION = 0.02; |
2c674647 |
5 | |
6 | require DynaLoader; |
7 | require Exporter; |
8 | |
51ef4e11 |
9 | our @ISA = qw(Exporter DynaLoader); |
2c674647 |
10 | |
4411f3b6 |
11 | # Public, encouraged API is exported by default |
51ef4e11 |
12 | our @EXPORT = qw ( |
4411f3b6 |
13 | encode |
14 | decode |
15 | encode_utf8 |
16 | decode_utf8 |
17 | find_encoding |
51ef4e11 |
18 | encodings |
4411f3b6 |
19 | ); |
20 | |
51ef4e11 |
21 | our @EXPORT_OK = |
2c674647 |
22 | qw( |
51ef4e11 |
23 | define_encoding |
24 | define_alias |
2c674647 |
25 | from_to |
26 | is_utf8 |
4411f3b6 |
27 | is_8bit |
28 | is_16bit |
a12c0f56 |
29 | utf8_upgrade |
30 | utf8_downgrade |
4411f3b6 |
31 | _utf8_on |
32 | _utf8_off |
2c674647 |
33 | ); |
34 | |
35 | bootstrap Encode (); |
36 | |
4411f3b6 |
37 | # Documentation moved after __END__ for speed - NI-S |
2c674647 |
38 | |
bf230f3d |
39 | use Carp; |
40 | |
51ef4e11 |
41 | # Make a %encoding package variable to allow a certain amount of cheating |
42 | our %encoding; |
43 | my @alias; # ordered matching list |
44 | my %alias; # cached known aliases |
5345d506 |
45 | |
656753f8 |
46 | sub encodings |
47 | { |
48 | my ($class) = @_; |
51ef4e11 |
49 | return keys %encoding; |
50 | } |
51 | |
52 | sub findAlias |
53 | { |
54 | my $class = shift; |
55 | local $_ = shift; |
56 | unless (exists $alias{$_}) |
656753f8 |
57 | { |
51ef4e11 |
58 | for (my $i=0; $i < @alias; $i += 2) |
656753f8 |
59 | { |
51ef4e11 |
60 | my $alias = $alias[$i]; |
61 | my $val = $alias[$i+1]; |
62 | my $new; |
63 | if (ref($alias) eq 'Regexp' && $_ =~ $alias) |
5345d506 |
64 | { |
51ef4e11 |
65 | $new = eval $val; |
66 | } |
67 | elsif (ref($alias) eq 'CODE') |
68 | { |
69 | $new = &{$alias}($val) |
70 | } |
71 | elsif (lc($_) eq $alias) |
72 | { |
73 | $new = $val; |
74 | } |
75 | if (defined($new)) |
76 | { |
77 | next if $new eq $_; # avoid (direct) recursion on bugs |
78 | my $enc = (ref($new)) ? $new : find_encoding($new); |
79 | if ($enc) |
5345d506 |
80 | { |
51ef4e11 |
81 | $alias{$_} = $enc; |
82 | last; |
5345d506 |
83 | } |
84 | } |
656753f8 |
85 | } |
5345d506 |
86 | } |
51ef4e11 |
87 | return $alias{$_}; |
5345d506 |
88 | } |
89 | |
51ef4e11 |
90 | sub define_alias |
5345d506 |
91 | { |
51ef4e11 |
92 | while (@_) |
5345d506 |
93 | { |
51ef4e11 |
94 | my ($alias,$name) = splice(@_,0,2); |
95 | push(@alias, $alias => $name); |
656753f8 |
96 | } |
51ef4e11 |
97 | } |
98 | |
016cb72c |
99 | # Allow variants of iso-8859-1 etc. |
d6089a2a |
100 | define_alias( qr/^iso[-_]?(\d+)[-_](\d+)$/i => '"iso-$1-$2"' ); |
016cb72c |
101 | |
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]"' ); |
106 | |
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'); |
113 | |
51ef4e11 |
114 | define_alias( 'ibm-1047' => 'cp1047'); |
115 | |
016cb72c |
116 | # Map white space and _ to '-' |
117 | define_alias( qr/^(\S+)[\s_]+(.*)$/i => '"$1-$2"' ); |
118 | |
51ef4e11 |
119 | sub define_encoding |
120 | { |
121 | my $obj = shift; |
122 | my $name = shift; |
123 | $encoding{$name} = $obj; |
124 | my $lc = lc($name); |
125 | define_alias($lc => $obj) unless $lc eq $name; |
126 | while (@_) |
656753f8 |
127 | { |
51ef4e11 |
128 | my $alias = shift; |
129 | define_alias($alias,$obj); |
656753f8 |
130 | } |
51ef4e11 |
131 | return $obj; |
656753f8 |
132 | } |
133 | |
656753f8 |
134 | sub getEncoding |
135 | { |
136 | my ($class,$name) = @_; |
5345d506 |
137 | my $enc; |
51ef4e11 |
138 | if (exists $encoding{$name}) |
656753f8 |
139 | { |
51ef4e11 |
140 | return $encoding{$name}; |
141 | } |
142 | else |
143 | { |
144 | return $class->findAlias($name); |
656753f8 |
145 | } |
656753f8 |
146 | } |
147 | |
4411f3b6 |
148 | sub find_encoding |
149 | { |
150 | my ($name) = @_; |
151 | return __PACKAGE__->getEncoding($name); |
152 | } |
153 | |
154 | sub encode |
155 | { |
156 | my ($name,$string,$check) = @_; |
157 | my $enc = find_encoding($name); |
158 | croak("Unknown encoding '$name'") unless defined $enc; |
50d26985 |
159 | my $octets = $enc->encode($string,$check); |
4411f3b6 |
160 | return undef if ($check && length($string)); |
161 | return $octets; |
162 | } |
163 | |
164 | sub decode |
165 | { |
166 | my ($name,$octets,$check) = @_; |
167 | my $enc = find_encoding($name); |
168 | croak("Unknown encoding '$name'") unless defined $enc; |
50d26985 |
169 | my $string = $enc->decode($octets,$check); |
4411f3b6 |
170 | return undef if ($check && length($octets)); |
171 | return $string; |
172 | } |
173 | |
174 | sub from_to |
175 | { |
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; |
50d26985 |
181 | my $uni = $f->decode($string,$check); |
4411f3b6 |
182 | return undef if ($check && length($string)); |
50d26985 |
183 | $string = $t->encode($uni,$check); |
4411f3b6 |
184 | return undef if ($check && length($uni)); |
185 | return length($_[0] = $string); |
186 | } |
187 | |
188 | sub encode_utf8 |
189 | { |
190 | my ($str) = @_; |
1b026014 |
191 | utf8::encode($str); |
4411f3b6 |
192 | return $str; |
193 | } |
194 | |
195 | sub decode_utf8 |
196 | { |
197 | my ($str) = @_; |
1b026014 |
198 | return undef unless utf8::decode($str); |
4411f3b6 |
199 | return $str; |
200 | } |
201 | |
50d26985 |
202 | package Encode::Encoding; |
203 | # Base class for classes which implement encodings |
4edaa979 |
204 | |
51ef4e11 |
205 | sub Define |
206 | { |
207 | my $obj = shift; |
208 | my $canonical = shift; |
209 | $obj = bless { Name => $canonical },$obj unless ref $obj; |
210 | # warn "$canonical => $obj\n"; |
211 | Encode::define_encoding($obj, $canonical, @_); |
212 | } |
213 | |
214 | sub name { shift->{'Name'} } |
215 | |
50d26985 |
216 | # Temporary legacy methods |
4edaa979 |
217 | sub toUnicode { shift->decode(@_) } |
218 | sub fromUnicode { shift->encode(@_) } |
219 | |
220 | sub new_sequence { return $_[0] } |
50d26985 |
221 | |
222 | package Encode::XS; |
223 | use base 'Encode::Encoding'; |
224 | |
656753f8 |
225 | package Encode::Unicode; |
50d26985 |
226 | use base 'Encode::Encoding'; |
656753f8 |
227 | |
9b37254d |
228 | # Dummy package that provides the encode interface but leaves data |
1b026014 |
229 | # as UTF-X encoded. It is here so that from_to() works. |
656753f8 |
230 | |
51ef4e11 |
231 | __PACKAGE__->Define('Unicode'); |
656753f8 |
232 | |
50d26985 |
233 | sub decode |
a12c0f56 |
234 | { |
235 | my ($obj,$str,$chk) = @_; |
1b026014 |
236 | utf8::upgrade($str); |
a12c0f56 |
237 | $_[1] = '' if $chk; |
238 | return $str; |
239 | } |
656753f8 |
240 | |
50d26985 |
241 | *encode = \&decode; |
656753f8 |
242 | |
4411f3b6 |
243 | package Encode::utf8; |
50d26985 |
244 | use base 'Encode::Encoding'; |
4411f3b6 |
245 | # package to allow long-hand |
246 | # $octets = encode( utf8 => $string ); |
247 | # |
248 | |
51ef4e11 |
249 | __PACKAGE__->Define(qw(UTF-8 utf8)); |
4411f3b6 |
250 | |
50d26985 |
251 | sub decode |
4411f3b6 |
252 | { |
253 | my ($obj,$octets,$chk) = @_; |
2a936312 |
254 | my $str = Encode::decode_utf8($octets); |
4411f3b6 |
255 | if (defined $str) |
256 | { |
257 | $_[1] = '' if $chk; |
258 | return $str; |
259 | } |
260 | return undef; |
261 | } |
262 | |
50d26985 |
263 | sub encode |
4411f3b6 |
264 | { |
265 | my ($obj,$string,$chk) = @_; |
2a936312 |
266 | my $octets = Encode::encode_utf8($string); |
4411f3b6 |
267 | $_[1] = '' if $chk; |
268 | return $octets; |
4411f3b6 |
269 | } |
270 | |
9b37254d |
271 | package Encode::iso10646_1; |
50d26985 |
272 | use base 'Encode::Encoding'; |
51ef4e11 |
273 | # Encoding is 16-bit network order Unicode (no surogates) |
9b37254d |
274 | # Used for X font encodings |
87714904 |
275 | |
8040349a |
276 | __PACKAGE__->Define(qw(UCS-2 iso-10646-1)); |
87714904 |
277 | |
50d26985 |
278 | sub decode |
87714904 |
279 | { |
280 | my ($obj,$str,$chk) = @_; |
281 | my $uni = ''; |
282 | while (length($str)) |
283 | { |
5dcbab34 |
284 | my $code = unpack('n',substr($str,0,2,'')) & 0xffff; |
87714904 |
285 | $uni .= chr($code); |
286 | } |
287 | $_[1] = $str if $chk; |
8040349a |
288 | utf8::upgrade($uni); |
87714904 |
289 | return $uni; |
290 | } |
291 | |
50d26985 |
292 | sub encode |
87714904 |
293 | { |
294 | my ($obj,$uni,$chk) = @_; |
295 | my $str = ''; |
296 | while (length($uni)) |
297 | { |
298 | my $ch = substr($uni,0,1,''); |
299 | my $x = ord($ch); |
300 | unless ($x < 32768) |
301 | { |
302 | last if ($chk); |
303 | $x = 0; |
304 | } |
5dcbab34 |
305 | $str .= pack('n',$x); |
656753f8 |
306 | } |
bf230f3d |
307 | $_[1] = $uni if $chk; |
656753f8 |
308 | return $str; |
309 | } |
310 | |
4411f3b6 |
311 | # switch back to Encode package in case we ever add AutoLoader |
312 | package Encode; |
313 | |
656753f8 |
314 | 1; |
315 | |
2a936312 |
316 | __END__ |
317 | |
4411f3b6 |
318 | =head1 NAME |
319 | |
320 | Encode - character encodings |
321 | |
322 | =head1 SYNOPSIS |
323 | |
324 | use Encode; |
325 | |
326 | =head1 DESCRIPTION |
327 | |
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>. |
330 | |
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>). |
337 | |
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. |
344 | |
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". |
348 | |
349 | =head2 TERMINOLOGY |
350 | |
4ac9195f |
351 | =over 4 |
4411f3b6 |
352 | |
353 | =item * |
354 | |
355 | I<character>: a character in the range 0..(2**32-1) (or more). |
356 | (What perl's strings are made of.) |
357 | |
358 | =item * |
359 | |
360 | I<byte>: a character in the range 0..255 |
361 | (A special case of a perl character.) |
362 | |
363 | =item * |
364 | |
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.) |
367 | |
368 | =back |
369 | |
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. |
373 | |
374 | =head1 ENCODINGS |
375 | |
376 | =head2 Characteristics of an Encoding |
377 | |
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. |
381 | |
382 | =head2 Types of Encodings |
383 | |
384 | Encodings can be divided into the following types: |
385 | |
386 | =over 4 |
387 | |
388 | =item * Fixed length 8-bit (or less) encodings. |
389 | |
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. |
392 | |
393 | =item * Fixed length 16-bit encodings |
394 | |
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. |
398 | |
399 | =item * Fixed length 32-bit encodings. |
400 | |
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. |
405 | |
406 | =item * Multi-byte encodings |
407 | |
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.) |
415 | |
416 | =item * "Escape" encodings. |
417 | |
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. |
424 | |
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. |
428 | |
429 | =back |
430 | |
431 | =head2 Specifying Encodings |
432 | |
433 | Encodings can be specified to the API described below in two ways: |
434 | |
435 | =over 4 |
436 | |
437 | =item 1. By name |
438 | |
439 | Encoding names are strings with characters taken from a restricted repertoire. |
440 | See L</"Encoding Names">. |
441 | |
442 | =item 2. As an object |
443 | |
444 | Encoding objects are returned by C<find_encoding($name)>. |
445 | |
446 | =back |
447 | |
448 | =head2 Encoding Names |
449 | |
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: |
454 | |
455 | =over 4 |
456 | |
457 | =item * The MIME name as defined in IETF RFC-XXXX. |
458 | |
459 | =item * The name in the IANA registry. |
460 | |
461 | =item * The name used by the the organization that defined it. |
462 | |
463 | =back |
464 | |
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. |
468 | |
4411f3b6 |
469 | =head1 PERL ENCODING API |
470 | |
471 | =head2 Generic Encoding Interface |
472 | |
473 | =over 4 |
474 | |
475 | =item * |
476 | |
477 | $bytes = encode(ENCODING, $string[, CHECK]) |
478 | |
479 | Encodes string from perl's internal form into I<ENCODING> and returns a |
480 | sequence of octets. |
481 | See L</"Handling Malformed Data">. |
482 | |
483 | =item * |
484 | |
485 | $string = decode(ENCODING, $bytes[, CHECK]) |
486 | |
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">. |
490 | |
491 | =back |
492 | |
493 | =head2 Handling Malformed Data |
494 | |
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. |
498 | |
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. |
501 | |
502 | It is also planned to allow I<CHECK> to be a code reference. |
503 | |
504 | This is not yet implemented as there are design issues with what its arguments |
505 | should be and how it returns its results. |
506 | |
507 | =over 4 |
508 | |
509 | =item Scheme 1 |
510 | |
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. |
514 | e.g. |
515 | |
516 | sub fixup { |
517 | my $ch = substr($_[0],0,1,''); |
518 | return sprintf("\x{%02X}",ord($ch); |
519 | } |
520 | |
521 | This scheme is close to how underlying C code for Encode works, but gives |
522 | the fixup routine very little context. |
523 | |
524 | =item Scheme 2 |
525 | |
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 |
529 | original string. |
530 | e.g. |
531 | |
532 | sub fixup { |
533 | # my ($s,$i,$d) = @_; |
534 | my $ch = substr($_[0],$_[1],1); |
535 | $_[2] .= sprintf("\x{%02X}",ord($ch); |
536 | return $_[1]+1; |
537 | } |
538 | |
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 |
541 | string intact. |
542 | |
543 | =item Other Schemes |
544 | |
545 | Hybrids of above. |
546 | |
547 | Multiple return values rather than in-place modifications. |
548 | |
549 | Index into the string could be pos($str) allowing s/\G...//. |
550 | |
551 | =back |
552 | |
553 | =head2 UTF-8 / utf8 |
554 | |
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). |
561 | |
562 | =over 4 |
563 | |
564 | =item * |
565 | |
566 | $bytes = encode_utf8($string); |
567 | |
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. |
571 | |
572 | =item * |
573 | |
574 | $string = decode_utf8($bytes [,CHECK]); |
575 | |
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">. |
580 | |
581 | =back |
582 | |
583 | =head2 Other Encodings of Unicode |
584 | |
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. |
588 | |
8040349a |
589 | Encode implements big-endian UCS-2 aliased to "iso-10646-1" as that |
4411f3b6 |
590 | happens to be the name used by that representation when used with X11 fonts. |
591 | |
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 |
595 | |
596 | pack('L',map(chr($_),split(//,$string))); # native |
597 | or |
598 | pack('V',map(chr($_),split(//,$string))); # little-endian |
599 | or |
600 | pack('N',map(chr($_),split(//,$string))); # big-endian |
601 | |
602 | depending on the endian required. |
603 | |
51ef4e11 |
604 | No UTF-32 encodings are implemented yet. |
4411f3b6 |
605 | |
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. |
608 | |
51ef4e11 |
609 | =head2 Listing available encodings |
610 | |
611 | use Encode qw(encodings); |
612 | @list = encodings(); |
613 | |
614 | Returns a list of the canonical names of the available encodings. |
615 | |
616 | =head2 Defining Aliases |
617 | |
618 | use Encode qw(define_alias); |
619 | define_alias( newName => ENCODING); |
620 | |
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). |
623 | |
624 | Currently I<newName> can be specified in the following ways: |
625 | |
626 | =over 4 |
627 | |
628 | =item As a simple string. |
629 | |
630 | =item As a qr// compiled regular expression, e.g.: |
631 | |
632 | define_alias( qr/^iso8859-(\d+)$/i => '"iso-8859-$1"' ); |
633 | |
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 |
637 | iso-8859-* family. |
638 | |
639 | =item As a code reference, e.g.: |
640 | |
641 | define_alias( sub { return /^iso8859-(\d+)$/i ? "iso-8859-$1" : undef } , ''); |
642 | |
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. |
647 | |
648 | =back |
649 | |
650 | =head2 Defining Encodings |
651 | |
652 | use Encode qw(define_alias); |
653 | define_encoding( $object, 'canonicalName' [,alias...]); |
654 | |
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>. |
659 | |
4411f3b6 |
660 | =head1 Encoding and IO |
661 | |
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. |
667 | |
51ef4e11 |
668 | open(my $ilyad,'>:encoding(iso-8859-7)','ilyad.greek'); |
4411f3b6 |
669 | print $ilyad @epic; |
670 | |
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): |
673 | |
674 | open(my $fh,'>:utf8','anything'); |
675 | print $fh "Any \x{0021} string \N{SMILEY FACE}\n"; |
676 | |
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>. |
679 | |
680 | Once a handle is open is layers can be altered using C<binmode>. |
681 | |
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 |
690 | and binary data. |
691 | |
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+/>, ...). |
696 | |
697 | =head1 Encoding How to ... |
698 | |
699 | To do: |
700 | |
701 | =over 4 |
702 | |
703 | =item * IO with mixed content (faking iso-2020-*) |
704 | |
705 | =item * MIME's Content-Length: |
706 | |
707 | =item * UTF-8 strings in binary data. |
708 | |
709 | =item * perl/Encode wrappers on non-Unicode XS modules. |
710 | |
711 | =back |
712 | |
713 | =head1 Messing with Perl's Internals |
714 | |
715 | The following API uses parts of perl's internals in the current implementation. |
716 | As such they are efficient, but may change. |
717 | |
718 | =over 4 |
719 | |
4411f3b6 |
720 | =item * is_utf8(STRING [, CHECK]) |
721 | |
722 | [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING. |
723 | If CHECK is true, also checks the data in STRING for being |
724 | well-formed UTF-8. Returns true if successful, false otherwise. |
725 | |
726 | =item * valid_utf8(STRING) |
727 | |
728 | [INTERNAL] Test whether STRING is in a consistent state. |
729 | Will return true if string is held as bytes, or is well-formed UTF-8 |
730 | and has the UTF-8 flag on. |
731 | Main reason for this routine is to allow perl's testsuite to check |
732 | that operations have left strings in a consistent state. |
733 | |
734 | =item * |
735 | |
736 | _utf8_on(STRING) |
737 | |
738 | [INTERNAL] Turn on the UTF-8 flag in STRING. The data in STRING is |
739 | B<not> checked for being well-formed UTF-8. Do not use unless you |
740 | B<know> that the STRING is well-formed UTF-8. Returns the previous |
741 | state of the UTF-8 flag (so please don't test the return value as |
742 | I<not> success or failure), or C<undef> if STRING is not a string. |
743 | |
744 | =item * |
745 | |
746 | _utf8_off(STRING) |
747 | |
748 | [INTERNAL] Turn off the UTF-8 flag in STRING. Do not use frivolously. |
749 | Returns the previous state of the UTF-8 flag (so please don't test the |
750 | return value as I<not> success or failure), or C<undef> if STRING is |
751 | not a string. |
752 | |
753 | =back |
754 | |
4edaa979 |
755 | =head1 IMPLEMENTATION CLASSES |
756 | |
757 | As mentioned above encodings are (in the current implementation at least) |
758 | defined by objects. The mapping of encoding name to object is via the |
51ef4e11 |
759 | C<%encodings> hash. |
4edaa979 |
760 | |
761 | The values of the hash can currently be either strings or objects. |
762 | The string form may go away in the future. The string form occurs |
763 | when C<encodings()> has scanned C<@INC> for loadable encodings but has |
764 | not actually loaded the encoding in question. This is because the |
765 | current "loading" process is all perl and a bit slow. |
766 | |
767 | Once an encoding is loaded then value of the hash is object which implements |
768 | the encoding. The object should provide the following interface: |
769 | |
770 | =over 4 |
771 | |
772 | =item -E<gt>name |
773 | |
774 | Should return the string representing the canonical name of the encoding. |
775 | |
776 | =item -E<gt>new_sequence |
777 | |
778 | This is a placeholder for encodings with state. It should return an object |
779 | which implements this interface, all current implementations return the |
780 | original object. |
781 | |
782 | =item -E<gt>encode($string,$check) |
783 | |
784 | Should return the octet sequence representing I<$string>. If I<$check> is true |
785 | it should modify I<$string> in place to remove the converted part (i.e. |
786 | the whole string unless there is an error). |
787 | If an error occurs it should return the octet sequence for the |
788 | fragment of string that has been converted, and modify $string in-place |
789 | to remove the converted part leaving it starting with the problem fragment. |
790 | |
791 | If check is is false then C<encode> should make a "best effort" to convert |
792 | the string - for example by using a replacement character. |
793 | |
794 | =item -E<gt>decode($octets,$check) |
795 | |
796 | Should return the string that I<$octets> represents. If I<$check> is true |
797 | it should modify I<$octets> in place to remove the converted part (i.e. |
798 | the whole sequence unless there is an error). |
799 | If an error occurs it should return the fragment of string |
800 | that has been converted, and modify $octets in-place to remove the converted part |
801 | leaving it starting with the problem fragment. |
802 | |
803 | If check is is false then C<decode> should make a "best effort" to convert |
804 | the string - for example by using Unicode's "\x{FFFD}" as a replacement character. |
805 | |
806 | =back |
807 | |
808 | It should be noted that the check behaviour is different from the outer |
809 | public API. The logic is that the "unchecked" case is useful when |
810 | encoding is part of a stream which may be reporting errors (e.g. STDERR). |
811 | In such cases it is desirable to get everything through somehow without |
812 | causing additional errors which obscure the original one. Also the encoding |
813 | is best placed to know what the correct replacement character is, so if that |
814 | is the desired behaviour then letting low level code do it is the most efficient. |
815 | |
816 | In contrast if check is true, the scheme above allows the encoding to do as |
817 | much as it can and tell layer above how much that was. What is lacking |
818 | at present is a mechanism to report what went wrong. The most likely interface |
819 | will be an additional method call to the object, or perhaps |
820 | (to avoid forcing per-stream objects on otherwise stateless encodings) |
821 | and additional parameter. |
822 | |
823 | It is also highly desirable that encoding classes inherit from C<Encode::Encoding> |
824 | as a base class. This allows that class to define additional behaviour for |
51ef4e11 |
825 | all encoding objects. For example built in Unicode, UCS-2 and UTF-8 classes |
826 | use : |
827 | |
828 | package Encode::MyEncoding; |
829 | use base qw(Encode::Encoding); |
830 | |
831 | __PACKAGE__->Define(qw(myCanonical myAlias)); |
832 | |
833 | To create an object with bless {Name => ...},$class, and call define_encoding. |
834 | They inherit their C<name> method from C<Encode::Encoding>. |
4edaa979 |
835 | |
836 | =head2 Compiled Encodings |
837 | |
838 | F<Encode.xs> provides a class C<Encode::XS> which provides the interface described |
839 | above. It calls a generic octet-sequence to octet-sequence "engine" that is |
840 | driven by tables (defined in F<encengine.c>). The same engine is used for both |
841 | encode and decode. C<Encode:XS>'s C<encode> forces perl's characters to their UTF-8 form |
842 | and then treats them as just another multibyte encoding. C<Encode:XS>'s C<decode> transforms |
843 | the sequence and then turns the UTF-8-ness flag as that is the form that the tables |
844 | are defined to produce. For details of the engine see the comments in F<encengine.c>. |
845 | |
846 | The tables are produced by the perl script F<compile> (the name needs to change so |
847 | we can eventually install it somewhere). F<compile> can currently read two formats: |
848 | |
849 | =over 4 |
850 | |
851 | =item *.enc |
852 | |
853 | This is a coined format used by Tcl. It is documented in Encode/EncodeFormat.pod. |
854 | |
855 | =item *.ucm |
856 | |
857 | This is the semi-standard format used by IBM's ICU package. |
858 | |
859 | =back |
860 | |
861 | F<compile> can write the following forms: |
862 | |
863 | =over 4 |
864 | |
865 | =item *.ucm |
866 | |
867 | See above - the F<Encode/*.ucm> files provided with the distribution have |
868 | been created from the original Tcl .enc files using this approach. |
869 | |
870 | =item *.c |
871 | |
872 | Produces tables as C data structures - this is used to build in encodings |
873 | into F<Encode.so>/F<Encode.dll>. |
874 | |
875 | =item *.xs |
876 | |
877 | In theory this allows encodings to be stand-alone loadable perl extensions. |
878 | The process has not yet been tested. The plan is to use this approach |
879 | for large East Asian encodings. |
880 | |
881 | =back |
882 | |
883 | The set of encodings built-in to F<Encode.so>/F<Encode.dll> is determined by |
884 | F<Makefile.PL>. The current set is as follows: |
885 | |
886 | =over 4 |
887 | |
888 | =item ascii and iso-8859-* |
889 | |
890 | That is all the common 8-bit "western" encodings. |
891 | |
892 | =item IBM-1047 and two other variants of EBCDIC. |
893 | |
894 | These are the same variants that are supported by EBCDIC perl as "native" encodings. |
895 | They are included to prove "reversibility" of some constructs in EBCDIC perl. |
896 | |
897 | =item symbol and dingbats as used by Tk on X11. |
898 | |
899 | (The reason Encode got started was to support perl/Tk.) |
900 | |
901 | =back |
902 | |
903 | That set is rather ad. hoc. and has been driven by the needs of the tests rather |
904 | than the needs of typical applications. It is likely to be rationalized. |
905 | |
4411f3b6 |
906 | =head1 SEE ALSO |
907 | |
908 | L<perlunicode>, L<perlebcdic>, L<perlfunc/open> |
909 | |
910 | =cut |
911 | |
912 | |
2a936312 |
913 | |