[ID 20011201.170] Time::HiRes in devel-perl causes segfaults for xs users
[p5sagit/p5-mst-13.2.git] / ext / Encode / Encode.pm
1 package Encode;
2 use strict;
3
4 our $VERSION = '0.02';
5
6 require DynaLoader;
7 require Exporter;
8
9 our @ISA = qw(Exporter DynaLoader);
10
11 # Public, encouraged API is exported by default
12 our @EXPORT = qw (
13   encode
14   decode
15   encode_utf8
16   decode_utf8
17   find_encoding
18   encodings
19 );
20
21 our @EXPORT_OK =
22     qw(
23        define_encoding
24        define_alias
25        from_to
26        is_utf8
27        is_8bit
28        is_16bit
29        utf8_upgrade
30        utf8_downgrade
31        _utf8_on
32        _utf8_off
33       );
34
35 bootstrap Encode ();
36
37 # Documentation moved after __END__ for speed - NI-S
38
39 use Carp;
40
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
45
46                      # 0  1  2  3  4  5   6   7   8   9  10
47 our @latin2iso_num = ( 0, 1, 2, 3, 4, 9, 10, 13, 14, 15, 16 );
48
49 our %winlatin2cp   = (
50                       'Latin1'     => 1252,
51                       'Latin2'     => 1250,
52                       'Cyrillic'   => 1251,
53                       'Greek'      => 1253,
54                       'Turkish'    => 1254,
55                       'Hebrew'     => 1255,
56                       'Arabic'     => 1256,
57                       'Baltic'     => 1257,
58                       'Vietnamese' => 1258,
59                      );
60
61 sub encodings
62 {
63  my ($class) = @_;
64  return keys %encoding;
65 }
66
67 sub findAlias
68 {
69  my $class = shift;
70  local $_ = shift;
71  # print "# findAlias $_\n";
72  unless (exists $alias{$_})
73   {
74    for (my $i=0; $i < @alias; $i += 2)
75     {
76      my $alias = $alias[$i];
77      my $val   = $alias[$i+1];
78      my $new;
79      if (ref($alias) eq 'Regexp' && $_ =~ $alias)
80       {
81        $new = eval $val;
82       }
83      elsif (ref($alias) eq 'CODE')
84       {
85        $new = &{$alias}($val)
86       }
87      elsif (lc($_) eq lc($alias))
88       {
89        $new = $val;
90       }
91      if (defined($new))
92       {
93        next if $new eq $_; # avoid (direct) recursion on bugs
94        my $enc = (ref($new)) ? $new : find_encoding($new);
95        if ($enc)
96         {
97          $alias{$_} = $enc;
98          last;
99         }
100       }
101     }
102   }
103  return $alias{$_};
104 }
105
106 sub define_alias
107 {
108  while (@_)
109   {
110    my ($alias,$name) = splice(@_,0,2);
111    push(@alias, $alias => $name);
112   }
113 }
114
115 # Allow variants of iso-8859-1 etc.
116 define_alias( qr/^iso[-_]?(\d+)[-_](\d+)$/i => '"iso-$1-$2"' );
117
118 # At least HP-UX has these.
119 define_alias( qr/^iso8859(\d+)$/i => '"iso-8859-$1"' );
120
121 # More HP stuff.
122 define_alias( qr/^(?:hp-)?(arabic|greek|hebrew|kana|roman|thai|turkish)8$/i => '"${1}8"' );
123
124 # The Official name of ASCII. 
125 define_alias( qr/^ANSI[-_]?X3\.4[-_]?1968$/i => '"ascii"' );
126
127 # This is a font issue, not an encoding issue.
128 # (The currency symbol of the Latin 1 upper half
129 #  has been redefined as the euro symbol.)
130 define_alias( qr/^(.+)\@euro$/i => '"$1"' );
131
132 # Allow latin-1 style names as well
133 define_alias( qr/^(?:iso[-_]?)?latin[-_]?(\d+)$/i => '"iso-8859-$latin2iso_num[$1]"' );
134
135 # Allow winlatin1 style names as well
136 define_alias( qr/^win(latin[12]|cyrillic|baltic|greek|turkish|hebrew|arabic|baltic|vietnamese)$/i => '"cp$winlatin2cp{\u$1}"' );
137
138 # Common names for non-latin prefered MIME names
139 define_alias( 'ascii'    => 'US-ascii',
140               'cyrillic' => 'iso-8859-5',
141               'arabic'   => 'iso-8859-6',
142               'greek'    => 'iso-8859-7',
143               'hebrew'   => 'iso-8859-8',
144               'thai'     => 'iso-8859-11',
145               'tis620'   => 'iso-8859-11',
146             );
147
148 # At least AIX has IBM-NNN (surprisingly...) instead of cpNNN.
149 define_alias( qr/^ibm[-_]?(\d\d\d\d?)$/i => '"cp$1"');
150
151 # Standardize on the dashed versions.
152 define_alias( qr/^utf8$/i  => 'utf-8' );
153 define_alias( qr/^koi8r$/i => 'koi8-r' );
154 define_alias( qr/^koi8u$/i => 'koi8-u' );
155
156 # TODO: HP-UX '8' encodings arabic8 greek8 hebrew8 kana8 thai8 turkish8
157 # TODO: HP-UX '15' encodings japanese15 korean15 roi15
158 # TODO: Cyrillic encoding ISO-IR-111 (useful?)
159 # TODO: Chinese encodings GB18030 GBK Big5-HSKCS EUC-TW
160 # TODO: Armenian encoding ARMSCII-8
161 # TODO: Hebrew encoding ISO-8859-8-1
162 # TODO: Thai encoding TCVN
163 # TODO: Korean encoding Johab
164 # TODO: Vietnamese encodings VPS
165 # TODO: Japanese encoding JIS (not the same as SJIS)
166 # TODO: Mac Asian+African encodings: Arabic Armenian Bengali Burmese
167 #       ChineseSimp ChineseTrad Devanagari Ethiopic ExtArabic
168 #       Farsi Georgian Gujarati Gurmukhi Hebrew Japanese
169 #       Kannada Khmer Korean Laotian Malayalam Mongolian
170 #       Oriya Sinhalese Symbol Tamil Telugu Tibetan Vietnamese
171 # TODO: what is the Japanese 'UJIS' encoding seen in some Linuxes?
172
173 # Map white space and _ to '-'
174 define_alias( qr/^(\S+)[\s_]+(.*)$/i => '"$1-$2"' );
175
176 sub define_encoding
177 {
178  my $obj  = shift;
179  my $name = shift;
180  $encoding{$name} = $obj;
181  my $lc = lc($name);
182  define_alias($lc => $obj) unless $lc eq $name;
183  while (@_)
184   {
185    my $alias = shift;
186    define_alias($alias,$obj);
187   }
188  return $obj;
189 }
190
191 sub getEncoding
192 {
193  my ($class,$name) = @_;
194  my $enc;
195  if (ref($name) && $name->can('new_sequence'))
196   {
197    return $name;
198   }
199  my $lc = lc $name;
200  if (exists $encoding{$name})
201   {
202    return $encoding{$name};
203   }
204  if (exists $encoding{$lc})
205   {
206    return $encoding{$lc};
207   }
208
209   my $oc = $class->findAlias($name);
210   return $oc if defined $oc;
211   return $class->findAlias($lc) if $lc ne $name;
212
213   return;
214 }
215
216 sub find_encoding
217 {
218  my ($name) = @_;
219  return __PACKAGE__->getEncoding($name);
220 }
221
222 sub encode
223 {
224  my ($name,$string,$check) = @_;
225  my $enc = find_encoding($name);
226  croak("Unknown encoding '$name'") unless defined $enc;
227  my $octets = $enc->encode($string,$check);
228  return undef if ($check && length($string));
229  return $octets;
230 }
231
232 sub decode
233 {
234  my ($name,$octets,$check) = @_;
235  my $enc = find_encoding($name);
236  croak("Unknown encoding '$name'") unless defined $enc;
237  my $string = $enc->decode($octets,$check);
238  $_[1] = $octets if $check;
239  return $string;
240 }
241
242 sub from_to
243 {
244  my ($string,$from,$to,$check) = @_;
245  my $f = find_encoding($from);
246  croak("Unknown encoding '$from'") unless defined $f;
247  my $t = find_encoding($to);
248  croak("Unknown encoding '$to'") unless defined $t;
249  my $uni = $f->decode($string,$check);
250  return undef if ($check && length($string));
251  $string = $t->encode($uni,$check);
252  return undef if ($check && length($uni));
253  return length($_[0] = $string);
254 }
255
256 sub encode_utf8
257 {
258  my ($str) = @_;
259  utf8::encode($str);
260  return $str;
261 }
262
263 sub decode_utf8
264 {
265  my ($str) = @_;
266  return undef unless utf8::decode($str);
267  return $str;
268 }
269
270 package Encode::Encoding;
271 # Base class for classes which implement encodings
272
273 sub Define
274 {
275  my $obj = shift;
276  my $canonical = shift;
277  $obj = bless { Name => $canonical },$obj unless ref $obj;
278  # warn "$canonical => $obj\n";
279  Encode::define_encoding($obj, $canonical, @_);
280 }
281
282 sub name { shift->{'Name'} }
283
284 # Temporary legacy methods
285 sub toUnicode    { shift->decode(@_) }
286 sub fromUnicode  { shift->encode(@_) }
287
288 sub new_sequence { return $_[0] }
289
290 package Encode::XS;
291 use base 'Encode::Encoding';
292
293 package Encode::Internal;
294 use base 'Encode::Encoding';
295
296 # Dummy package that provides the encode interface but leaves data
297 # as UTF-X encoded. It is here so that from_to() works.
298
299 __PACKAGE__->Define('Internal');
300
301 Encode::define_alias( 'Unicode' => 'Internal' ) if ord('A') == 65;
302
303 sub decode
304 {
305  my ($obj,$str,$chk) = @_;
306  utf8::upgrade($str);
307  $_[1] = '' if $chk;
308  return $str;
309 }
310
311 *encode = \&decode;
312
313 package Encoding::Unicode;
314 use base 'Encode::Encoding';
315
316 __PACKAGE__->Define('Unicode') unless ord('A') == 65;
317
318 sub decode
319 {
320  my ($obj,$str,$chk) = @_;
321  my $res = '';
322  for (my $i = 0; $i < length($str); $i++)
323   {
324    $res .= chr(utf8::unicode_to_native(ord(substr($str,$i,1))));
325   }
326  $_[1] = '' if $chk;
327  return $res;
328 }
329
330 sub encode
331 {
332  my ($obj,$str,$chk) = @_;
333  my $res = '';
334  for (my $i = 0; $i < length($str); $i++)
335   {
336    $res .= chr(utf8::native_to_unicode(ord(substr($str,$i,1))));
337   }
338  $_[1] = '' if $chk;
339  return $res;
340 }
341
342
343 package Encode::utf8;
344 use base 'Encode::Encoding';
345 # package to allow long-hand
346 #   $octets = encode( utf8 => $string );
347 #
348
349 __PACKAGE__->Define(qw(UTF-8 utf8));
350
351 sub decode
352 {
353  my ($obj,$octets,$chk) = @_;
354  my $str = Encode::decode_utf8($octets);
355  if (defined $str)
356   {
357    $_[1] = '' if $chk;
358    return $str;
359   }
360  return undef;
361 }
362
363 sub encode
364 {
365  my ($obj,$string,$chk) = @_;
366  my $octets = Encode::encode_utf8($string);
367  $_[1] = '' if $chk;
368  return $octets;
369 }
370
371 package Encode::iso10646_1;
372 use base 'Encode::Encoding';
373 # Encoding is 16-bit network order Unicode (no surogates)
374 # Used for X font encodings
375
376 __PACKAGE__->Define(qw(UCS-2 iso-10646-1));
377
378 sub decode
379 {
380  my ($obj,$str,$chk) = @_;
381  my $uni   = '';
382  while (length($str))
383   {
384    my $code = unpack('n',substr($str,0,2,'')) & 0xffff;
385    $uni .= chr($code);
386   }
387  $_[1] = $str if $chk;
388  utf8::upgrade($uni);
389  return $uni;
390 }
391
392 sub encode
393 {
394  my ($obj,$uni,$chk) = @_;
395  my $str   = '';
396  while (length($uni))
397   {
398    my $ch = substr($uni,0,1,'');
399    my $x  = ord($ch);
400    unless ($x < 32768)
401     {
402      last if ($chk);
403      $x = 0;
404     }
405    $str .= pack('n',$x);
406   }
407  $_[1] = $uni if $chk;
408  return $str;
409 }
410
411 package Encode::ucs_2le;
412 use base 'Encode::Encoding';
413
414 __PACKAGE__->Define(qw(UCS-2le UCS-2LE ucs-2le));
415
416 sub decode
417 {
418  my ($obj,$str,$chk) = @_;
419  my $uni   = '';
420  while (length($str))
421  {
422   my $code = unpack('v',substr($str,0,2,'')) & 0xffff;
423   $uni .= chr($code);
424  }
425  $_[1] = $str if $chk;
426  utf8::upgrade($uni);
427  return $uni;
428 }
429
430 sub encode
431 {
432  my ($obj,$uni,$chk) = @_;
433  my $str   = '';
434  while (length($uni))
435  {
436   my $ch = substr($uni,0,1,'');
437   my $x  = ord($ch);
438   unless ($x < 32768)
439   {
440    last if ($chk);
441    $x = 0;
442   }
443   $str .= pack('v',$x);
444  }
445  $_[1] = $uni if $chk;
446  return $str;
447 }
448
449 # switch back to Encode package in case we ever add AutoLoader
450 package Encode;
451
452 1;
453
454 __END__
455
456 =head1 NAME
457
458 Encode - character encodings
459
460 =head1 SYNOPSIS
461
462     use Encode;
463
464 =head1 DESCRIPTION
465
466 The C<Encode> module provides the interfaces between Perl's strings
467 and the rest of the system.  Perl strings are sequences of B<characters>.
468
469 The repertoire of characters that Perl can represent is at least that
470 defined by the Unicode Consortium. On most platforms the ordinal
471 values of the characters (as returned by C<ord(ch)>) is the "Unicode
472 codepoint" for the character (the exceptions are those platforms where
473 the legacy encoding is some variant of EBCDIC rather than a super-set
474 of ASCII - see L<perlebcdic>).
475
476 Traditionaly computer data has been moved around in 8-bit chunks
477 often called "bytes". These chunks are also known as "octets" in
478 networking standards. Perl is widely used to manipulate data of
479 many types - not only strings of characters representing human or
480 computer languages but also "binary" data being the machines representation
481 of numbers, pixels in an image - or just about anything.
482
483 When Perl is processing "binary data" the programmer wants Perl to process
484 "sequences of bytes". This is not a problem for Perl - as a byte has 256
485 possible values it easily fits in Perl's much larger "logical character".
486
487 =head2 TERMINOLOGY
488
489 =over 4
490
491 =item *
492
493 I<character>: a character in the range 0..(2**32-1) (or more).
494 (What Perl's strings are made of.)
495
496 =item *
497
498 I<byte>: a character in the range 0..255
499 (A special case of a Perl character.)
500
501 =item *
502
503 I<octet>: 8 bits of data, with ordinal values 0..255
504 (Term for bytes passed to or from a non-Perl context, e.g. disk file.)
505
506 =back
507
508 The marker [INTERNAL] marks Internal Implementation Details, in
509 general meant only for those who think they know what they are doing,
510 and such details may change in future releases.
511
512 =head1 ENCODINGS
513
514 =head2 Characteristics of an Encoding
515
516 An encoding has a "repertoire" of characters that it can represent,
517 and for each representable character there is at least one sequence of
518 octets that represents it.
519
520 =head2 Types of Encodings
521
522 Encodings can be divided into the following types:
523
524 =over 4
525
526 =item * Fixed length 8-bit (or less) encodings.
527
528 Each character is a single octet so may have a repertoire of up to
529 256 characters. ASCII and iso-8859-* are typical examples.
530
531 =item * Fixed length 16-bit encodings
532
533 Each character is two octets so may have a repertoire of up to
534 65 536 characters.  Unicode's UCS-2 is an example.  Also used for
535 encodings for East Asian languages.
536
537 =item * Fixed length 32-bit encodings.
538
539 Not really very "encoded" encodings. The Unicode code points
540 are just represented as 4-octet integers. None the less because
541 different architectures use different representations of integers
542 (so called "endian") there at least two disctinct encodings.
543
544 =item * Multi-byte encodings
545
546 The number of octets needed to represent a character varies.
547 UTF-8 is a particularly complex but regular case of a multi-byte
548 encoding. Several East Asian countries use a multi-byte encoding
549 where 1-octet is used to cover western roman characters and Asian
550 characters get 2-octets.
551 (UTF-16 is strictly a multi-byte encoding taking either 2 or 4 octets
552 to represent a Unicode code point.)
553
554 =item * "Escape" encodings.
555
556 These encodings embed "escape sequences" into the octet sequence
557 which describe how the following octets are to be interpreted.
558 The iso-2022-* family is typical. Following the escape sequence
559 octets are encoded by an "embedded" encoding (which will be one
560 of the above types) until another escape sequence switches to
561 a different "embedded" encoding.
562
563 These schemes are very flexible and can handle mixed languages but are
564 very complex to process (and have state).  No escape encodings are
565 implemented for Perl yet.
566
567 =back
568
569 =head2 Specifying Encodings
570
571 Encodings can be specified to the API described below in two ways:
572
573 =over 4
574
575 =item 1. By name
576
577 Encoding names are strings with characters taken from a restricted
578 repertoire.  See L</"Encoding Names">.
579
580 =item 2. As an object
581
582 Encoding objects are returned by C<find_encoding($name)>.
583
584 =back
585
586 =head2 Encoding Names
587
588 Encoding names are case insensitive. White space in names is ignored.
589 In addition an encoding may have aliases. Each encoding has one
590 "canonical" name.  The "canonical" name is chosen from the names of
591 the encoding by picking the first in the following sequence:
592
593 =over 4
594
595 =item * The MIME name as defined in IETF RFCs.
596
597 =item * The name in the IANA registry.
598
599 =item * The name used by the organization that defined it.
600
601 =back
602
603 Because of all the alias issues, and because in the general case
604 encodings have state C<Encode> uses the encoding object internally
605 once an operation is in progress.
606
607 As of Perl 5.8.0, at least the following encodings are recognized
608 (the => marks aliases):
609
610   ASCII
611
612   US-ASCII => ASCII
613
614 The Unicode:
615
616   UTF-8   
617   UTF-16
618   UCS-2
619
620   ISO 10646-1 => UCS-2
621
622 The ISO 8859 and KOI:
623
624   ISO 8859-1  ISO 8859-6   ISO 8859-11         KOI8-F
625   ISO 8859-2  ISO 8859-7   (12 doesn't exist)  KOI8-R
626   ISO 8859-3  ISO 8859-8   ISO 8859-13         KOI8-U
627   ISO 8859-4  ISO 8859-9   ISO 8859-14
628   ISO 8859-5  ISO 8859-10  ISO 8859-15
629                            ISO 8859-16
630
631   Latin1  => 8859-1  Latin6  => 8859-10
632   Latin2  => 8859-2  Latin7  => 8859-13
633   Latin3  => 8859-3  Latin8  => 8859-14 
634   Latin4  => 8859-4  Latin9  => 8859-15
635   Latin5  => 8859-9  Latin10 => 8859-16
636
637   Cyrillic => 8859-5
638   Arabic   => 8859-6
639   Greek    => 8859-7
640   Hebrew   => 8859-8
641   Thai     => 8859-11
642   TIS620   => 8859-11 
643
644 The CJKV: Chinese, Japanese, Korean, Vietnamese:
645
646   ISO 2022     ISO 2022 JP-1  JIS 0201  GB 1988   Big5       EUC-CN       
647   ISO 2022 CN  ISO 2022 JP-2  JIS 0208  GB 2312   HZ         EUC-JP     
648   ISO 2022 JP  ISO 2022 KR    JIS 0210  GB 12345  CNS 11643  EUC-JP-0212
649   Shift-JIS                                                  EUC-KR     
650   VISCII
651
652 The PC codepages:
653
654   CP37   CP852  CP861  CP866  CP949   CP1251  CP1256
655   CP424  CP855  CP862  CP869  CP950   CP1252  CP1257
656   CP737  CP856  CP863  CP874  CP1006  CP1253  CP1258
657   CP775  CP857  CP864  CP932  CP1047  CP1254
658   CP850  CP860  CP865  CP936  CP1250  CP1255
659
660   WinLatin1     => CP1252
661   WinLatin2     => CP1250
662   WinCyrillic   => CP1251
663   WinGreek      => CP1253
664   WinTurkiskh   => CP1254
665   WinHebrew     => CP1255
666   WinArabic     => CP1256
667   WinBaltic     => CP1257
668   WinVietnamese => CP1258
669
670 (All the CPI<NNN...> are available also as IBMI<NNN...>.)
671
672 The Mac codepages:
673
674   MacCentralEuropean   MacJapanese        
675   MacCroatian          MacRoman           
676   MacCyrillic          MacRumanian        
677   MacDingbats          MacSami            
678   MacGreek             MacThai            
679   MacIcelandic         MacTurkish         
680                        MacUkraine         
681
682 Miscellaneous:
683
684   7bit-greek  IR-197
685   7bit-kana   NeXTstep
686   7bit-latin1 POSIX-BC
687   DingBats    Roman8
688   GSM 0338    Symbol
689
690 =head1 PERL ENCODING API
691
692 =head2 Generic Encoding Interface
693
694 =over 4
695
696 =item *
697
698         $bytes  = encode(ENCODING, $string[, CHECK])
699
700 Encodes string from Perl's internal form into I<ENCODING> and returns
701 a sequence of octets.  For CHECK see L</"Handling Malformed Data">.
702
703 For example to convert (internally UTF-8 encoded) Unicode data
704 to octets:
705
706         $octets = encode("utf8", $unicode);
707
708 =item *
709
710         $string = decode(ENCODING, $bytes[, CHECK])
711
712 Decode sequence of octets assumed to be in I<ENCODING> into Perl's
713 internal form and returns the resulting string.  For CHECK see
714 L</"Handling Malformed Data">.
715
716 For example to convert ISO 8859-1 data to UTF-8:
717
718         $utf8 = decode("latin1", $latin1);
719
720 =item *
721
722         from_to($string, FROM_ENCODING, TO_ENCODING[, CHECK])
723
724 Convert B<in-place> the data between two encodings.  How did the data
725 in $string originally get to be in FROM_ENCODING?  Either using
726 encode() or through PerlIO: See L</"Encoding and IO">.  For CHECK
727 see L</"Handling Malformed Data">.
728
729 For example to convert ISO 8859-1 data to UTF-8:
730
731         from_to($data, "iso-8859-1", "utf-8");
732
733 and to convert it back:
734
735         from_to($data, "utf-8", "iso-8859-1");
736
737 Note that because the conversion happens in place, the data to be
738 converted cannot be a string constant, it must be a scalar variable.
739
740 =back
741
742 =head2 Handling Malformed Data
743
744 If CHECK is not set, C<undef> is returned.  If the data is supposed to
745 be UTF-8, an optional lexical warning (category utf8) is given.  If
746 CHECK is true but not a code reference, dies.
747
748 It would desirable to have a way to indicate that transform should use
749 the encodings "replacement character" - no such mechanism is defined yet.
750
751 It is also planned to allow I<CHECK> to be a code reference.
752
753 This is not yet implemented as there are design issues with what its
754 arguments should be and how it returns its results.
755
756 =over 4
757
758 =item Scheme 1
759
760 Passed remaining fragment of string being processed.
761 Modifies it in place to remove bytes/characters it can understand
762 and returns a string used to represent them.
763 e.g.
764
765  sub fixup {
766    my $ch = substr($_[0],0,1,'');
767    return sprintf("\x{%02X}",ord($ch);
768  }
769
770 This scheme is close to how underlying C code for Encode works, but gives
771 the fixup routine very little context.
772
773 =item Scheme 2
774
775 Passed original string, and an index into it of the problem area, and
776 output string so far.  Appends what it will to output string and
777 returns new index into original string.  For example:
778
779  sub fixup {
780    # my ($s,$i,$d) = @_;
781    my $ch = substr($_[0],$_[1],1);
782    $_[2] .= sprintf("\x{%02X}",ord($ch);
783    return $_[1]+1;
784  }
785
786 This scheme gives maximal control to the fixup routine but is more
787 complicated to code, and may need internals of Encode to be tweaked to
788 keep original string intact.
789
790 =item Other Schemes
791
792 Hybrids of above.
793
794 Multiple return values rather than in-place modifications.
795
796 Index into the string could be pos($str) allowing s/\G...//.
797
798 =back
799
800 =head2 UTF-8 / utf8
801
802 The Unicode consortium defines the UTF-8 standard as a way of encoding
803 the entire Unicode repertiore as sequences of octets.  This encoding is
804 expected to become very widespread. Perl can use this form internaly
805 to represent strings, so conversions to and from this form are
806 particularly efficient (as octets in memory do not have to change,
807 just the meta-data that tells Perl how to treat them).
808
809 =over 4
810
811 =item *
812
813         $bytes = encode_utf8($string);
814
815 The characters that comprise string are encoded in Perl's superset of UTF-8
816 and the resulting octets returned as a sequence of bytes. All possible
817 characters have a UTF-8 representation so this function cannot fail.
818
819 =item *
820
821         $string = decode_utf8($bytes [,CHECK]);
822
823 The sequence of octets represented by $bytes is decoded from UTF-8
824 into a sequence of logical characters. Not all sequences of octets
825 form valid UTF-8 encodings, so it is possible for this call to fail.
826 For CHECK see L</"Handling Malformed Data">.
827
828 =back
829
830 =head2 Other Encodings of Unicode
831
832 UTF-16 is similar to UCS-2, 16 bit or 2-byte chunks.  UCS-2 can only
833 represent 0..0xFFFF, while UTF-16 has a I<surrogate pair> scheme which
834 allows it to cover the whole Unicode range.
835
836 Surrogates are code points set aside to encode the 0x01000..0x10FFFF
837 range of Unicode code points in pairs of 16-bit units.  The I<high
838 surrogates> are the range 0xD800..0xDBFF, and the I<low surrogates>
839 are the range 0xDC00..0xDFFFF.  The surrogate encoding is
840
841         $hi = ($uni - 0x10000) / 0x400 + 0xD800;
842         $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
843
844 and the decoding is
845
846         $uni = 0x10000 + ($hi - 0xD8000) * 0x400 + ($lo - 0xDC00);
847
848 Encode implements big-endian UCS-2 aliased to "iso-10646-1" as that
849 happens to be the name used by that representation when used with X11
850 fonts.
851
852 UTF-32 or UCS-4 is 32-bit or 4-byte chunks.  Perl's logical characters
853 can be considered as being in this form without encoding. An encoding
854 to transfer strings in this form (e.g. to write them to a file) would
855 need to
856
857      pack('L*', unpack('U*', $string));  # native
858   or
859      pack('V*', unpack('U*', $string));  # little-endian
860   or
861      pack('N*', unpack('U*', $string));  # big-endian
862
863 depending on the endianness required.
864
865 No UTF-32 encodings are implemented yet.
866
867 Both UCS-2 and UCS-4 style encodings can have "byte order marks" by
868 representing the code point 0xFFFE as the very first thing in a file.
869
870 =head2 Listing available encodings
871
872   use Encode qw(encodings);
873   @list = encodings();
874
875 Returns a list of the canonical names of the available encodings.
876
877 =head2 Defining Aliases
878
879   use Encode qw(define_alias);
880   define_alias( newName => ENCODING);
881
882 Allows newName to be used as am alias for ENCODING. ENCODING may be
883 either the name of an encoding or and encoding object (as above).
884
885 Currently I<newName> can be specified in the following ways:
886
887 =over 4
888
889 =item As a simple string.
890
891 =item As a qr// compiled regular expression, e.g.:
892
893   define_alias( qr/^iso8859-(\d+)$/i => '"iso-8859-$1"' );
894
895 In this case if I<ENCODING> is not a reference it is C<eval>-ed to
896 allow C<$1> etc. to be subsituted.  The example is one way to names as
897 used in X11 font names to alias the MIME names for the iso-8859-*
898 family.
899
900 =item As a code reference, e.g.:
901
902   define_alias( sub { return /^iso8859-(\d+)$/i ? "iso-8859-$1" : undef } , '');
903
904 In this case C<$_> will be set to the name that is being looked up and
905 I<ENCODING> is passed to the sub as its first argument.  The example
906 is another way to names as used in X11 font names to alias the MIME
907 names for the iso-8859-* family.
908
909 =back
910
911 =head2 Defining Encodings
912
913     use Encode qw(define_alias);
914     define_encoding( $object, 'canonicalName' [,alias...]);
915
916 Causes I<canonicalName> to be associated with I<$object>.  The object
917 should provide the interface described in L</"IMPLEMENTATION CLASSES">
918 below.  If more than two arguments are provided then additional
919 arguments are taken as aliases for I<$object> as for C<define_alias>.
920
921 =head1 Encoding and IO
922
923 It is very common to want to do encoding transformations when
924 reading or writing files, network connections, pipes etc.
925 If Perl is configured to use the new 'perlio' IO system then
926 C<Encode> provides a "layer" (See L<perliol>) which can transform
927 data as it is read or written.
928
929 Here is how the blind poet would modernise the encoding:
930
931     use Encode;
932     open(my $iliad,'<:encoding(iso-8859-7)','iliad.greek');
933     open(my $utf8,'>:utf8','iliad.utf8');
934     my @epic = <$iliad>;
935     print $utf8 @epic;
936     close($utf8);
937     close($illiad);
938
939 In addition the new IO system can also be configured to read/write
940 UTF-8 encoded characters (as noted above this is efficient):
941
942     open(my $fh,'>:utf8','anything');
943     print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
944
945 Either of the above forms of "layer" specifications can be made the default
946 for a lexical scope with the C<use open ...> pragma. See L<open>.
947
948 Once a handle is open is layers can be altered using C<binmode>.
949
950 Without any such configuration, or if Perl itself is built using
951 system's own IO, then write operations assume that file handle accepts
952 only I<bytes> and will C<die> if a character larger than 255 is
953 written to the handle. When reading, each octet from the handle
954 becomes a byte-in-a-character. Note that this default is the same
955 behaviour as bytes-only languages (including Perl before v5.6) would
956 have, and is sufficient to handle native 8-bit encodings
957 e.g. iso-8859-1, EBCDIC etc. and any legacy mechanisms for handling
958 other encodings and binary data.
959
960 In other cases it is the programs responsibility to transform
961 characters into bytes using the API above before doing writes, and to
962 transform the bytes read from a handle into characters before doing
963 "character operations" (e.g. C<lc>, C</\W+/>, ...).
964
965 You can also use PerlIO to convert larger amounts of data you don't
966 want to bring into memory.  For example to convert between ISO 8859-1
967 (Latin 1) and UTF-8 (or UTF-EBCDIC in EBCDIC machines):
968
969     open(F, "<:encoding(iso-8859-1)", "data.txt") or die $!;
970     open(G, ">:utf8",                 "data.utf") or die $!;
971     while (<F>) { print G }
972
973     # Could also do "print G <F>" but that would pull
974     # the whole file into memory just to write it out again.
975
976 More examples:
977
978     open(my $f, "<:encoding(cp1252)")
979     open(my $g, ">:encoding(iso-8859-2)")
980     open(my $h, ">:encoding(latin9)")       # iso-8859-15
981
982 See L<PerlIO> for more information.
983
984 See also L<encoding> for how to change the default encoding of the
985 data in your script.
986
987 =head1 Encoding How to ...
988
989 To do:
990
991 =over 4
992
993 =item * IO with mixed content (faking iso-2020-*)
994
995 =item * MIME's Content-Length:
996
997 =item * UTF-8 strings in binary data.
998
999 =item * Perl/Encode wrappers on non-Unicode XS modules.
1000
1001 =back
1002
1003 =head1 Messing with Perl's Internals
1004
1005 The following API uses parts of Perl's internals in the current
1006 implementation.  As such they are efficient, but may change.
1007
1008 =over 4
1009
1010 =item * is_utf8(STRING [, CHECK])
1011
1012 [INTERNAL] Test whether the UTF-8 flag is turned on in the STRING.
1013 If CHECK is true, also checks the data in STRING for being well-formed
1014 UTF-8.  Returns true if successful, false otherwise.
1015
1016 =item * valid_utf8(STRING)
1017
1018 [INTERNAL] Test whether STRING is in a consistent state.  Will return
1019 true if string is held as bytes, or is well-formed UTF-8 and has the
1020 UTF-8 flag on.  Main reason for this routine is to allow Perl's
1021 testsuite to check that operations have left strings in a consistent
1022 state.
1023
1024 =item *
1025
1026         _utf8_on(STRING)
1027
1028 [INTERNAL] Turn on the UTF-8 flag in STRING.  The data in STRING is
1029 B<not> checked for being well-formed UTF-8.  Do not use unless you
1030 B<know> that the STRING is well-formed UTF-8.  Returns the previous
1031 state of the UTF-8 flag (so please don't test the return value as
1032 I<not> success or failure), or C<undef> if STRING is not a string.
1033
1034 =item *
1035
1036         _utf8_off(STRING)
1037
1038 [INTERNAL] Turn off the UTF-8 flag in STRING.  Do not use frivolously.
1039 Returns the previous state of the UTF-8 flag (so please don't test the
1040 return value as I<not> success or failure), or C<undef> if STRING is
1041 not a string.
1042
1043 =back
1044
1045 =head1 IMPLEMENTATION CLASSES
1046
1047 As mentioned above encodings are (in the current implementation at least)
1048 defined by objects. The mapping of encoding name to object is via the
1049 C<%encodings> hash.
1050
1051 The values of the hash can currently be either strings or objects.
1052 The string form may go away in the future. The string form occurs
1053 when C<encodings()> has scanned C<@INC> for loadable encodings but has
1054 not actually loaded the encoding in question. This is because the
1055 current "loading" process is all Perl and a bit slow.
1056
1057 Once an encoding is loaded then value of the hash is object which
1058 implements the encoding. The object should provide the following
1059 interface:
1060
1061 =over 4
1062
1063 =item -E<gt>name
1064
1065 Should return the string representing the canonical name of the encoding.
1066
1067 =item -E<gt>new_sequence
1068
1069 This is a placeholder for encodings with state. It should return an
1070 object which implements this interface, all current implementations
1071 return the original object.
1072
1073 =item -E<gt>encode($string,$check)
1074
1075 Should return the octet sequence representing I<$string>. If I<$check>
1076 is true it should modify I<$string> in place to remove the converted
1077 part (i.e.  the whole string unless there is an error).  If an error
1078 occurs it should return the octet sequence for the fragment of string
1079 that has been converted, and modify $string in-place to remove the
1080 converted part leaving it starting with the problem fragment.
1081
1082 If check is is false then C<encode> should make a "best effort" to
1083 convert the string - for example by using a replacement character.
1084
1085 =item -E<gt>decode($octets,$check)
1086
1087 Should return the string that I<$octets> represents. If I<$check> is
1088 true it should modify I<$octets> in place to remove the converted part
1089 (i.e.  the whole sequence unless there is an error).  If an error
1090 occurs it should return the fragment of string that has been
1091 converted, and modify $octets in-place to remove the converted part
1092 leaving it starting with the problem fragment.
1093
1094 If check is is false then C<decode> should make a "best effort" to
1095 convert the string - for example by using Unicode's "\x{FFFD}" as a
1096 replacement character.
1097
1098 =back
1099
1100 It should be noted that the check behaviour is different from the
1101 outer public API. The logic is that the "unchecked" case is useful
1102 when encoding is part of a stream which may be reporting errors
1103 (e.g. STDERR).  In such cases it is desirable to get everything
1104 through somehow without causing additional errors which obscure the
1105 original one. Also the encoding is best placed to know what the
1106 correct replacement character is, so if that is the desired behaviour
1107 then letting low level code do it is the most efficient.
1108
1109 In contrast if check is true, the scheme above allows the encoding to
1110 do as much as it can and tell layer above how much that was. What is
1111 lacking at present is a mechanism to report what went wrong. The most
1112 likely interface will be an additional method call to the object, or
1113 perhaps (to avoid forcing per-stream objects on otherwise stateless
1114 encodings) and additional parameter.
1115
1116 It is also highly desirable that encoding classes inherit from
1117 C<Encode::Encoding> as a base class. This allows that class to define
1118 additional behaviour for all encoding objects. For example built in
1119 Unicode, UCS-2 and UTF-8 classes use :
1120
1121   package Encode::MyEncoding;
1122   use base qw(Encode::Encoding);
1123
1124   __PACKAGE__->Define(qw(myCanonical myAlias));
1125
1126 To create an object with bless {Name => ...},$class, and call
1127 define_encoding.  They inherit their C<name> method from
1128 C<Encode::Encoding>.
1129
1130 =head2 Compiled Encodings
1131
1132 F<Encode.xs> provides a class C<Encode::XS> which provides the
1133 interface described above. It calls a generic octet-sequence to
1134 octet-sequence "engine" that is driven by tables (defined in
1135 F<encengine.c>). The same engine is used for both encode and
1136 decode. C<Encode:XS>'s C<encode> forces Perl's characters to their
1137 UTF-8 form and then treats them as just another multibyte
1138 encoding. C<Encode:XS>'s C<decode> transforms the sequence and then
1139 turns the UTF-8-ness flag as that is the form that the tables are
1140 defined to produce. For details of the engine see the comments in
1141 F<encengine.c>.
1142
1143 The tables are produced by the Perl script F<compile> (the name needs
1144 to change so we can eventually install it somewhere). F<compile> can
1145 currently read two formats:
1146
1147 =over 4
1148
1149 =item *.enc
1150
1151 This is a coined format used by Tcl. It is documented in
1152 Encode/EncodeFormat.pod.
1153
1154 =item *.ucm
1155
1156 This is the semi-standard format used by IBM's ICU package.
1157
1158 =back
1159
1160 F<compile> can write the following forms:
1161
1162 =over 4
1163
1164 =item *.ucm
1165
1166 See above - the F<Encode/*.ucm> files provided with the distribution have
1167 been created from the original Tcl .enc files using this approach.
1168
1169 =item *.c
1170
1171 Produces tables as C data structures - this is used to build in encodings
1172 into F<Encode.so>/F<Encode.dll>.
1173
1174 =item *.xs
1175
1176 In theory this allows encodings to be stand-alone loadable Perl
1177 extensions.  The process has not yet been tested. The plan is to use
1178 this approach for large East Asian encodings.
1179
1180 =back
1181
1182 The set of encodings built-in to F<Encode.so>/F<Encode.dll> is
1183 determined by F<Makefile.PL>.  The current set is as follows:
1184
1185 =over 4
1186
1187 =item ascii and iso-8859-*
1188
1189 That is all the common 8-bit "western" encodings.
1190
1191 =item IBM-1047 and two other variants of EBCDIC.
1192
1193 These are the same variants that are supported by EBCDIC Perl as
1194 "native" encodings.  They are included to prove "reversibility" of
1195 some constructs in EBCDIC Perl.
1196
1197 =item symbol and dingbats as used by Tk on X11.
1198
1199 (The reason Encode got started was to support Perl/Tk.)
1200
1201 =back
1202
1203 That set is rather ad hoc and has been driven by the needs of the
1204 tests rather than the needs of typical applications. It is likely
1205 to be rationalized.
1206
1207 =head1 SEE ALSO
1208
1209 L<perlunicode>, L<perlebcdic>, L<perlfunc/open>, L<PerlIO>, L<encoding>
1210
1211 =cut
1212