This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
c34e997d0405914c7e6d0cf6a21f0a492cddcc59
[perl5.git] / cpan / Encode / Encode.pm
1 #
2 # $Id: Encode.pm,v 2.68 2015/01/22 10:17:32 dankogai Exp dankogai $
3 #
4 package Encode;
5 use strict;
6 use warnings;
7 our $VERSION = sprintf "%d.%02d", q$Revision: 2.68 $ =~ /(\d+)/g;
8 use constant DEBUG => !!$ENV{PERL_ENCODE_DEBUG};
9 use XSLoader ();
10 XSLoader::load( __PACKAGE__, $VERSION );
11
12 use Exporter 5.57 'import';
13
14 # Public, encouraged API is exported by default
15
16 our @EXPORT = qw(
17   decode  decode_utf8  encode  encode_utf8 str2bytes bytes2str
18   encodings  find_encoding clone_encoding
19 );
20 our @FB_FLAGS = qw(
21   DIE_ON_ERR WARN_ON_ERR RETURN_ON_ERR LEAVE_SRC
22   PERLQQ HTMLCREF XMLCREF STOP_AT_PARTIAL
23 );
24 our @FB_CONSTS = qw(
25   FB_DEFAULT FB_CROAK FB_QUIET FB_WARN
26   FB_PERLQQ FB_HTMLCREF FB_XMLCREF
27 );
28 our @EXPORT_OK = (
29     qw(
30       _utf8_off _utf8_on define_encoding from_to is_16bit is_8bit
31       is_utf8 perlio_ok resolve_alias utf8_downgrade utf8_upgrade
32       ),
33     @FB_FLAGS, @FB_CONSTS,
34 );
35
36 our %EXPORT_TAGS = (
37     all          => [ @EXPORT,    @EXPORT_OK ],
38     default      => [ @EXPORT ],
39     fallbacks    => [ @FB_CONSTS ],
40     fallback_all => [ @FB_CONSTS, @FB_FLAGS ],
41 );
42
43 # Documentation moved after __END__ for speed - NI-S
44
45 our $ON_EBCDIC = ( ord("A") == 193 );
46
47 use Encode::Alias;
48
49 # Make a %Encoding package variable to allow a certain amount of cheating
50 our %Encoding;
51 our %ExtModule;
52 require Encode::Config;
53 #  See
54 #  https://bugzilla.redhat.com/show_bug.cgi?id=435505#c2
55 #  to find why sig handlers inside eval{} are disabled.
56 eval {
57     local $SIG{__DIE__};
58     local $SIG{__WARN__};
59     require Encode::ConfigLocal;
60 };
61
62 sub encodings {
63     my %enc;
64     my $arg  = $_[1] || '';
65     if ( $arg eq ":all" ) {
66         %enc = ( %Encoding, %ExtModule );
67     }
68     else {
69         %enc = %Encoding;
70         for my $mod ( map { m/::/ ? $_ : "Encode::$_" } @_ ) {
71             DEBUG and warn $mod;
72             for my $enc ( keys %ExtModule ) {
73                 $ExtModule{$enc} eq $mod and $enc{$enc} = $mod;
74             }
75         }
76     }
77     return sort { lc $a cmp lc $b }
78       grep      { !/^(?:Internal|Unicode|Guess)$/o } keys %enc;
79 }
80
81 sub perlio_ok {
82     my $obj = ref( $_[0] ) ? $_[0] : find_encoding( $_[0] );
83     $obj->can("perlio_ok") and return $obj->perlio_ok();
84     return 0;    # safety net
85 }
86
87 sub define_encoding {
88     my $obj  = shift;
89     my $name = shift;
90     $Encoding{$name} = $obj;
91     my $lc = lc($name);
92     define_alias( $lc => $obj ) unless $lc eq $name;
93     while (@_) {
94         my $alias = shift;
95         define_alias( $alias, $obj );
96     }
97     return $obj;
98 }
99
100 sub getEncoding {
101     my ( $class, $name, $skip_external ) = @_;
102
103     $name =~ s/\s+//g; # https://rt.cpan.org/Ticket/Display.html?id=65796
104
105     ref($name) && $name->can('renew') and return $name;
106     exists $Encoding{$name} and return $Encoding{$name};
107     my $lc = lc $name;
108     exists $Encoding{$lc} and return $Encoding{$lc};
109
110     my $oc = $class->find_alias($name);
111     defined($oc) and return $oc;
112     $lc ne $name and $oc = $class->find_alias($lc);
113     defined($oc) and return $oc;
114
115     unless ($skip_external) {
116         if ( my $mod = $ExtModule{$name} || $ExtModule{$lc} ) {
117             $mod =~ s,::,/,g;
118             $mod .= '.pm';
119             eval { require $mod; };
120             exists $Encoding{$name} and return $Encoding{$name};
121         }
122     }
123     return;
124 }
125
126 sub find_encoding($;$) {
127     my ( $name, $skip_external ) = @_;
128     return __PACKAGE__->getEncoding( $name, $skip_external );
129 }
130
131 sub resolve_alias($) {
132     my $obj = find_encoding(shift);
133     defined $obj and return $obj->name;
134     return;
135 }
136
137 sub clone_encoding($) {
138     my $obj = find_encoding(shift);
139     ref $obj or return;
140     eval { require Storable };
141     $@ and return;
142     return Storable::dclone($obj);
143 }
144
145 sub encode($$;$) {
146     my ( $name, $string, $check ) = @_;
147     return undef unless defined $string;
148     $string .= '';    # stringify;
149     $check ||= 0;
150     unless ( defined $name ) {
151         require Carp;
152         Carp::croak("Encoding name should not be undef");
153     }
154     my $enc = find_encoding($name);
155     unless ( defined $enc ) {
156         require Carp;
157         Carp::croak("Unknown encoding '$name'");
158     }
159     # For Unicode, warnings need to be caught and re-issued at this level
160     # so that callers can disable utf8 warnings lexically.
161     my $octets;
162     if ( ref($enc) eq 'Encode::Unicode' ) {
163         my $warn = '';
164         {
165             local $SIG{__WARN__} = sub { $warn = shift };
166             $octets = $enc->encode( $string, $check );
167         }
168         warnings::warnif('utf8', $warn) if length $warn;
169     }
170     else {
171         $octets = $enc->encode( $string, $check );
172     }
173     $_[1] = $string if $check and !ref $check and !( $check & LEAVE_SRC() );
174     return $octets;
175 }
176 *str2bytes = \&encode;
177
178 sub decode($$;$) {
179     my ( $name, $octets, $check ) = @_;
180     return undef unless defined $octets;
181     $octets .= '';
182     $check ||= 0;
183     my $enc = find_encoding($name);
184     unless ( defined $enc ) {
185         require Carp;
186         Carp::croak("Unknown encoding '$name'");
187     }
188     # For Unicode, warnings need to be caught and re-issued at this level
189     # so that callers can disable utf8 warnings lexically.
190     my $string;
191     if ( ref($enc) eq 'Encode::Unicode' ) {
192         my $warn = '';
193         {
194             local $SIG{__WARN__} = sub { $warn = shift };
195             $string = $enc->decode( $octets, $check );
196         }
197         warnings::warnif('utf8', $warn) if length $warn;
198     }
199     else {
200         $string = $enc->decode( $octets, $check );
201     }
202     $_[1] = $octets if $check and !ref $check and !( $check & LEAVE_SRC() );
203     return $string;
204 }
205 *bytes2str = \&decode;
206
207 sub from_to($$$;$) {
208     my ( $string, $from, $to, $check ) = @_;
209     return undef unless defined $string;
210     $check ||= 0;
211     my $f = find_encoding($from);
212     unless ( defined $f ) {
213         require Carp;
214         Carp::croak("Unknown encoding '$from'");
215     }
216     my $t = find_encoding($to);
217     unless ( defined $t ) {
218         require Carp;
219         Carp::croak("Unknown encoding '$to'");
220     }
221     my $uni = $f->decode($string);
222     $_[0] = $string = $t->encode( $uni, $check );
223     return undef if ( $check && length($uni) );
224     return defined( $_[0] ) ? length($string) : undef;
225 }
226
227 sub encode_utf8($) {
228     my ($str) = @_;
229     utf8::encode($str);
230     return $str;
231 }
232
233 my $utf8enc;
234
235 sub decode_utf8($;$) {
236     my ( $octets, $check ) = @_;
237     return undef unless defined $octets;
238     $octets .= '';
239     $check   ||= 0;
240     $utf8enc ||= find_encoding('utf8');
241     my $string = $utf8enc->decode( $octets, $check );
242     $_[0] = $octets if $check and !ref $check and !( $check & LEAVE_SRC() );
243     return $string;
244 }
245
246 # sub decode_utf8($;$) {
247 #     my ( $str, $check ) = @_;
248 #     return $str if is_utf8($str);
249 #     if ($check) {
250 #         return decode( "utf8", $str, $check );
251 #     }
252 #     else {
253 #         return decode( "utf8", $str );
254 #         return $str;
255 #     }
256 # }
257
258 predefine_encodings(1);
259
260 #
261 # This is to restore %Encoding if really needed;
262 #
263
264 sub predefine_encodings {
265     require Encode::Encoding;
266     no warnings 'redefine';
267     my $use_xs = shift;
268     if ($ON_EBCDIC) {
269
270         # was in Encode::UTF_EBCDIC
271         package Encode::UTF_EBCDIC;
272         push @Encode::UTF_EBCDIC::ISA, 'Encode::Encoding';
273         *decode = sub {
274             my ( undef, $str, $chk ) = @_;
275             my $res = '';
276             for ( my $i = 0 ; $i < length($str) ; $i++ ) {
277                 $res .=
278                   chr(
279                     utf8::unicode_to_native( ord( substr( $str, $i, 1 ) ) )
280                   );
281             }
282             $_[1] = '' if $chk;
283             return $res;
284         };
285         *encode = sub {
286             my ( undef, $str, $chk ) = @_;
287             my $res = '';
288             for ( my $i = 0 ; $i < length($str) ; $i++ ) {
289                 $res .=
290                   chr(
291                     utf8::native_to_unicode( ord( substr( $str, $i, 1 ) ) )
292                   );
293             }
294             $_[1] = '' if $chk;
295             return $res;
296         };
297         $Encode::Encoding{Unicode} =
298           bless { Name => "UTF_EBCDIC" } => "Encode::UTF_EBCDIC";
299     }
300     else {
301
302         package Encode::Internal;
303         push @Encode::Internal::ISA, 'Encode::Encoding';
304         *decode = sub {
305             my ( undef, $str, $chk ) = @_;
306             utf8::upgrade($str);
307             $_[1] = '' if $chk;
308             return $str;
309         };
310         *encode = \&decode;
311         $Encode::Encoding{Unicode} =
312           bless { Name => "Internal" } => "Encode::Internal";
313     }
314
315     {
316
317         # was in Encode::utf8
318         package Encode::utf8;
319         push @Encode::utf8::ISA, 'Encode::Encoding';
320
321         #
322         if ($use_xs) {
323             Encode::DEBUG and warn __PACKAGE__, " XS on";
324             *decode = \&decode_xs;
325             *encode = \&encode_xs;
326         }
327         else {
328             Encode::DEBUG and warn __PACKAGE__, " XS off";
329             *decode = sub {
330                 my ( undef, $octets, $chk ) = @_;
331                 my $str = Encode::decode_utf8($octets);
332                 if ( defined $str ) {
333                     $_[1] = '' if $chk;
334                     return $str;
335                 }
336                 return undef;
337             };
338             *encode = sub {
339                 my ( undef, $string, $chk ) = @_;
340                 my $octets = Encode::encode_utf8($string);
341                 $_[1] = '' if $chk;
342                 return $octets;
343             };
344         }
345         *cat_decode = sub {    # ($obj, $dst, $src, $pos, $trm, $chk)
346                                # currently ignores $chk
347             my ( undef, undef, undef, $pos, $trm ) = @_;
348             my ( $rdst, $rsrc, $rpos ) = \@_[ 1, 2, 3 ];
349             use bytes;
350             if ( ( my $npos = index( $$rsrc, $trm, $pos ) ) >= 0 ) {
351                 $$rdst .=
352                   substr( $$rsrc, $pos, $npos - $pos + length($trm) );
353                 $$rpos = $npos + length($trm);
354                 return 1;
355             }
356             $$rdst .= substr( $$rsrc, $pos );
357             $$rpos = length($$rsrc);
358             return '';
359         };
360         $Encode::Encoding{utf8} =
361           bless { Name => "utf8" } => "Encode::utf8";
362         $Encode::Encoding{"utf-8-strict"} =
363           bless { Name => "utf-8-strict", strict_utf8 => 1 } 
364             => "Encode::utf8";
365     }
366 }
367
368 1;
369
370 __END__
371
372 =head1 NAME
373
374 Encode - character encodings in Perl
375
376 =head1 SYNOPSIS
377
378     use Encode qw(decode encode);
379     $characters = decode('UTF-8', $octets,     Encode::FB_CROAK);
380     $octets     = encode('UTF-8', $characters, Encode::FB_CROAK);
381
382 =head2 Table of Contents
383
384 Encode consists of a collection of modules whose details are too extensive
385 to fit in one document.  This one itself explains the top-level APIs
386 and general topics at a glance.  For other topics and more details,
387 see the documentation for these modules:
388
389 =over 2
390
391 =item L<Encode::Alias> - Alias definitions to encodings
392
393 =item L<Encode::Encoding> - Encode Implementation Base Class
394
395 =item L<Encode::Supported> - List of Supported Encodings
396
397 =item L<Encode::CN> - Simplified Chinese Encodings
398
399 =item L<Encode::JP> - Japanese Encodings
400
401 =item L<Encode::KR> - Korean Encodings
402
403 =item L<Encode::TW> - Traditional Chinese Encodings
404
405 =back
406
407 =head1 DESCRIPTION
408
409 The C<Encode> module provides the interface between Perl strings
410 and the rest of the system.  Perl strings are sequences of
411 I<characters>.
412
413 The repertoire of characters that Perl can represent is a superset of those
414 defined by the Unicode Consortium. On most platforms the ordinal
415 values of a character as returned by C<ord(I<S>)> is the I<Unicode
416 codepoint> for that character. The exceptions are platforms where
417 the legacy encoding is some variant of EBCDIC rather than a superset
418 of ASCII; see L<perlebcdic>.
419
420 During recent history, data is moved around a computer in 8-bit chunks,
421 often called "bytes" but also known as "octets" in standards documents.
422 Perl is widely used to manipulate data of many types: not only strings of
423 characters representing human or computer languages, but also "binary"
424 data, being the machine's representation of numbers, pixels in an image, or
425 just about anything.
426
427 When Perl is processing "binary data", the programmer wants Perl to
428 process "sequences of bytes". This is not a problem for Perl: because a
429 byte has 256 possible values, it easily fits in Perl's much larger
430 "logical character".
431
432 This document mostly explains the I<how>. L<perlunitut> and L<perlunifaq>
433 explain the I<why>.
434
435 =head2 TERMINOLOGY
436
437 =head3 character
438
439 A character in the range 0 .. 2**32-1 (or more);
440 what Perl's strings are made of.
441
442 =head3 byte
443
444 A character in the range 0..255;
445 a special case of a Perl character.
446
447 =head3 octet
448
449 8 bits of data, with ordinal values 0..255;
450 term for bytes passed to or from a non-Perl context, such as a disk file,
451 standard I/O stream, database, command-line argument, environment variable,
452 socket etc.
453
454 =head1 THE PERL ENCODING API
455
456 =head2 Basic methods
457
458 =head3 encode
459
460   $octets  = encode(ENCODING, STRING[, CHECK])
461
462 Encodes the scalar value I<STRING> from Perl's internal form into
463 I<ENCODING> and returns a sequence of octets.  I<ENCODING> can be either a
464 canonical name or an alias.  For encoding names and aliases, see
465 L</"Defining Aliases">.  For CHECK, see L</"Handling Malformed Data">.
466
467 For example, to convert a string from Perl's internal format into
468 ISO-8859-1, also known as Latin1:
469
470   $octets = encode("iso-8859-1", $string);
471
472 B<CAVEAT>: When you run C<$octets = encode("utf8", $string)>, then
473 $octets I<might not be equal to> $string.  Though both contain the
474 same data, the UTF8 flag for $octets is I<always> off.  When you
475 encode anything, the UTF8 flag on the result is always off, even when it
476 contains a completely valid utf8 string. See L</"The UTF8 flag"> below.
477
478 If the $string is C<undef>, then C<undef> is returned.
479
480 =head3 decode
481
482   $string = decode(ENCODING, OCTETS[, CHECK])
483
484 This function returns the string that results from decoding the scalar
485 value I<OCTETS>, assumed to be a sequence of octets in I<ENCODING>, into
486 Perl's internal form.  As with encode(),
487 I<ENCODING> can be either a canonical name or an alias. For encoding names
488 and aliases, see L</"Defining Aliases">; for I<CHECK>, see L</"Handling
489 Malformed Data">.
490
491 For example, to convert ISO-8859-1 data into a string in Perl's
492 internal format:
493
494   $string = decode("iso-8859-1", $octets);
495
496 B<CAVEAT>: When you run C<$string = decode("utf8", $octets)>, then $string
497 I<might not be equal to> $octets.  Though both contain the same data, the
498 UTF8 flag for $string is on.  See L</"The UTF8 flag">
499 below.
500
501 If the $string is C<undef>, then C<undef> is returned.
502
503 =head3 find_encoding
504
505   [$obj =] find_encoding(ENCODING)
506
507 Returns the I<encoding object> corresponding to I<ENCODING>.  Returns
508 C<undef> if no matching I<ENCODING> is find.  The returned object is
509 what does the actual encoding or decoding.
510
511   $utf8 = decode($name, $bytes);
512
513 is in fact
514
515     $utf8 = do {
516         $obj = find_encoding($name);
517         croak qq(encoding "$name" not found) unless ref $obj;
518         $obj->decode($bytes);
519     };
520
521 with more error checking.
522
523 You can therefore save time by reusing this object as follows;
524
525     my $enc = find_encoding("iso-8859-1");
526     while(<>) {
527         my $utf8 = $enc->decode($_);
528         ... # now do something with $utf8;
529     }
530
531 Besides L</decode> and L</encode>, other methods are
532 available as well.  For instance, C<name()> returns the canonical
533 name of the encoding object.
534
535   find_encoding("latin1")->name; # iso-8859-1
536
537 See L<Encode::Encoding> for details.
538
539 =head3 from_to
540
541   [$length =] from_to($octets, FROM_ENC, TO_ENC [, CHECK])
542
543 Converts I<in-place> data between two encodings. The data in $octets
544 must be encoded as octets and I<not> as characters in Perl's internal
545 format. For example, to convert ISO-8859-1 data into Microsoft's CP1250
546 encoding:
547
548   from_to($octets, "iso-8859-1", "cp1250");
549
550 and to convert it back:
551
552   from_to($octets, "cp1250", "iso-8859-1");
553
554 Because the conversion happens in place, the data to be
555 converted cannot be a string constant: it must be a scalar variable.
556
557 C<from_to()> returns the length of the converted string in octets on success,
558 and C<undef> on error.
559
560 B<CAVEAT>: The following operations may look the same, but are not:
561
562   from_to($data, "iso-8859-1", "utf8"); #1
563   $data = decode("iso-8859-1", $data);  #2
564
565 Both #1 and #2 make $data consist of a completely valid UTF-8 string,
566 but only #2 turns the UTF8 flag on.  #1 is equivalent to:
567
568   $data = encode("utf8", decode("iso-8859-1", $data));
569
570 See L</"The UTF8 flag"> below.
571
572 Also note that:
573
574   from_to($octets, $from, $to, $check);
575
576 is equivalent to:
577
578   $octets = encode($to, decode($from, $octets), $check);
579
580 Yes, it does I<not> respect the $check during decoding.  It is
581 deliberately done that way.  If you need minute control, use C<decode>
582 followed by C<encode> as follows:
583
584   $octets = encode($to, decode($from, $octets, $check_from), $check_to);
585
586 =head3 encode_utf8
587
588   $octets = encode_utf8($string);
589
590 Equivalent to C<$octets = encode("utf8", $string)>.  The characters in
591 $string are encoded in Perl's internal format, and the result is returned
592 as a sequence of octets.  Because all possible characters in Perl have a
593 (loose, not strict) UTF-8 representation, this function cannot fail.
594
595 =head3 decode_utf8
596
597   $string = decode_utf8($octets [, CHECK]);
598
599 Equivalent to C<$string = decode("utf8", $octets [, CHECK])>.
600 The sequence of octets represented by $octets is decoded
601 from UTF-8 into a sequence of logical characters.
602 Because not all sequences of octets are valid UTF-8,
603 it is quite possible for this function to fail.
604 For CHECK, see L</"Handling Malformed Data">.
605
606 =head2 Listing available encodings
607
608   use Encode;
609   @list = Encode->encodings();
610
611 Returns a list of canonical names of available encodings that have already
612 been loaded.  To get a list of all available encodings including those that
613 have not yet been loaded, say:
614
615   @all_encodings = Encode->encodings(":all");
616
617 Or you can give the name of a specific module:
618
619   @with_jp = Encode->encodings("Encode::JP");
620
621 When "C<::>" is not in the name, "C<Encode::>" is assumed.
622
623   @ebcdic = Encode->encodings("EBCDIC");
624
625 To find out in detail which encodings are supported by this package,
626 see L<Encode::Supported>.
627
628 =head2 Defining Aliases
629
630 To add a new alias to a given encoding, use:
631
632   use Encode;
633   use Encode::Alias;
634   define_alias(NEWNAME => ENCODING);
635
636 After that, I<NEWNAME> can be used as an alias for I<ENCODING>.
637 I<ENCODING> may be either the name of an encoding or an
638 I<encoding object>.
639
640 Before you do that, first make sure the alias is nonexistent using
641 C<resolve_alias()>, which returns the canonical name thereof.
642 For example:
643
644   Encode::resolve_alias("latin1") eq "iso-8859-1" # true
645   Encode::resolve_alias("iso-8859-12")   # false; nonexistent
646   Encode::resolve_alias($name) eq $name  # true if $name is canonical
647
648 C<resolve_alias()> does not need C<use Encode::Alias>; it can be
649 imported via C<use Encode qw(resolve_alias)>.
650
651 See L<Encode::Alias> for details.
652
653 =head2 Finding IANA Character Set Registry names
654
655 The canonical name of a given encoding does not necessarily agree with
656 IANA Character Set Registry, commonly seen as C<< Content-Type:
657 text/plain; charset=I<WHATEVER> >>.  For most cases, the canonical name
658 works, but sometimes it does not, most notably with "utf-8-strict".
659
660 As of C<Encode> version 2.21, a new method C<mime_name()> is therefore added.
661
662   use Encode;
663   my $enc = find_encoding("UTF-8");
664   warn $enc->name;      # utf-8-strict
665   warn $enc->mime_name; # UTF-8
666
667 See also:  L<Encode::Encoding>
668
669 =head1 Encoding via PerlIO
670
671 If your perl supports C<PerlIO> (which is the default), you can use a
672 C<PerlIO> layer to decode and encode directly via a filehandle.  The
673 following two examples are fully identical in functionality:
674
675   ### Version 1 via PerlIO
676     open(INPUT,  "< :encoding(shiftjis)", $infile)
677         || die "Can't open < $infile for reading: $!";
678     open(OUTPUT, "> :encoding(euc-jp)",  $outfile)
679         || die "Can't open > $output for writing: $!";
680     while (<INPUT>) {   # auto decodes $_
681         print OUTPUT;   # auto encodes $_
682     }
683     close(INPUT)   || die "can't close $infile: $!";
684     close(OUTPUT)  || die "can't close $outfile: $!";
685
686   ### Version 2 via from_to()
687     open(INPUT,  "< :raw", $infile)
688         || die "Can't open < $infile for reading: $!";
689     open(OUTPUT, "> :raw",  $outfile)
690         || die "Can't open > $output for writing: $!";
691
692     while (<INPUT>) {
693         from_to($_, "shiftjis", "euc-jp", 1);  # switch encoding
694         print OUTPUT;   # emit raw (but properly encoded) data
695     }
696     close(INPUT)   || die "can't close $infile: $!";
697     close(OUTPUT)  || die "can't close $outfile: $!";
698
699 In the first version above, you let the appropriate encoding layer
700 handle the conversion.  In the second, you explicitly translate
701 from one encoding to the other.
702
703 Unfortunately, it may be that encodings are not C<PerlIO>-savvy.  You can check
704 to see whether your encoding is supported by C<PerlIO> by invoking the
705 C<perlio_ok> method on it:
706
707   Encode::perlio_ok("hz");             # false
708   find_encoding("euc-cn")->perlio_ok;  # true wherever PerlIO is available
709
710   use Encode qw(perlio_ok);            # imported upon request
711   perlio_ok("euc-jp")
712
713 Fortunately, all encodings that come with C<Encode> core are C<PerlIO>-savvy
714 except for C<hz> and C<ISO-2022-kr>.  For the gory details, see
715 L<Encode::Encoding> and L<Encode::PerlIO>.
716
717 =head1 Handling Malformed Data
718
719 The optional I<CHECK> argument tells C<Encode> what to do when
720 encountering malformed data.  Without I<CHECK>, C<Encode::FB_DEFAULT>
721 (== 0) is assumed.
722
723 As of version 2.12, C<Encode> supports coderef values for C<CHECK>;
724 see below.
725
726 B<NOTE:> Not all encodings support this feature.
727 Some encodings ignore the I<CHECK> argument.  For example,
728 L<Encode::Unicode> ignores I<CHECK> and it always croaks on error.
729
730 =head2 List of I<CHECK> values
731
732 =head3 FB_DEFAULT
733
734   I<CHECK> = Encode::FB_DEFAULT ( == 0)
735
736 If I<CHECK> is 0, encoding and decoding replace any malformed character
737 with a I<substitution character>.  When you encode, I<SUBCHAR> is used.
738 When you decode, the Unicode REPLACEMENT CHARACTER, code point U+FFFD, is
739 used.  If the data is supposed to be UTF-8, an optional lexical warning of
740 warning category C<"utf8"> is given.
741
742 =head3 FB_CROAK
743
744   I<CHECK> = Encode::FB_CROAK ( == 1)
745
746 If I<CHECK> is 1, methods immediately die with an error
747 message.  Therefore, when I<CHECK> is 1, you should trap
748 exceptions with C<eval{}>, unless you really want to let it C<die>.
749
750 =head3 FB_QUIET
751
752   I<CHECK> = Encode::FB_QUIET
753
754 If I<CHECK> is set to C<Encode::FB_QUIET>, encoding and decoding immediately
755 return the portion of the data that has been processed so far when an
756 error occurs. The data argument is overwritten with everything
757 after that point; that is, the unprocessed portion of the data.  This is
758 handy when you have to call C<decode> repeatedly in the case where your
759 source data may contain partial multi-byte character sequences,
760 (that is, you are reading with a fixed-width buffer). Here's some sample
761 code to do exactly that:
762
763     my($buffer, $string) = ("", "");
764     while (read($fh, $buffer, 256, length($buffer))) {
765         $string .= decode($encoding, $buffer, Encode::FB_QUIET);
766         # $buffer now contains the unprocessed partial character
767     }
768
769 =head3 FB_WARN
770
771   I<CHECK> = Encode::FB_WARN
772
773 This is the same as C<FB_QUIET> above, except that instead of being silent
774 on errors, it issues a warning.  This is handy for when you are debugging.
775
776 =head3 FB_PERLQQ FB_HTMLCREF FB_XMLCREF
777
778 =over 2
779
780 =item perlqq mode (I<CHECK> = Encode::FB_PERLQQ)
781
782 =item HTML charref mode (I<CHECK> = Encode::FB_HTMLCREF)
783
784 =item XML charref mode (I<CHECK> = Encode::FB_XMLCREF)
785
786 =back
787
788 For encodings that are implemented by the C<Encode::XS> module, C<CHECK> C<==>
789 C<Encode::FB_PERLQQ> puts C<encode> and C<decode> into C<perlqq> fallback mode.
790
791 When you decode, C<\xI<HH>> is inserted for a malformed character, where
792 I<HH> is the hex representation of the octet that could not be decoded to
793 utf8.  When you encode, C<\x{I<HHHH>}> will be inserted, where I<HHHH> is
794 the Unicode code point (in any number of hex digits) of the character that
795 cannot be found in the character repertoire of the encoding.
796
797 The HTML/XML character reference modes are about the same. In place of
798 C<\x{I<HHHH>}>, HTML uses C<&#I<NNN>;> where I<NNN> is a decimal number, and
799 XML uses C<&#xI<HHHH>;> where I<HHHH> is the hexadecimal number.
800
801 In C<Encode> 2.10 or later, C<LEAVE_SRC> is also implied.
802
803 =head3 The bitmask
804
805 These modes are all actually set via a bitmask.  Here is how the C<FB_I<XXX>>
806 constants are laid out.  You can import the C<FB_I<XXX>> constants via
807 C<use Encode qw(:fallbacks)>, and you can import the generic bitmask
808 constants via C<use Encode qw(:fallback_all)>.
809
810                      FB_DEFAULT FB_CROAK FB_QUIET FB_WARN  FB_PERLQQ
811  DIE_ON_ERR    0x0001             X
812  WARN_ON_ERR   0x0002                               X
813  RETURN_ON_ERR 0x0004                      X        X
814  LEAVE_SRC     0x0008                                        X
815  PERLQQ        0x0100                                        X
816  HTMLCREF      0x0200
817  XMLCREF       0x0400
818
819 =head3 LEAVE_SRC
820
821   Encode::LEAVE_SRC
822
823 If the C<Encode::LEAVE_SRC> bit is I<not> set but I<CHECK> is set, then the
824 source string to encode() or decode() will be overwritten in place.
825 If you're not interested in this, then bitwise-OR it with the bitmask.
826
827 =head2 coderef for CHECK
828
829 As of C<Encode> 2.12, C<CHECK> can also be a code reference which takes the
830 ordinal value of the unmapped character as an argument and returns
831 octets that represent the fallback character.  For instance:
832
833   $ascii = encode("ascii", $utf8, sub{ sprintf "<U+%04X>", shift });
834
835 Acts like C<FB_PERLQQ> but U+I<XXXX> is used instead of C<\x{I<XXXX>}>.
836
837 Even the fallback for C<decode> must return octets, which are
838 then decoded with the character encoding that C<decode> accepts. So for
839 example if you wish to decode octets as UTF-8, and use ISO-8859-15 as
840 a fallback for bytes that are not valid UTF-8, you could write
841
842     $str = decode 'UTF-8', $octets, sub {
843         my $tmp = chr shift;
844         from_to $tmp, 'ISO-8859-15', 'UTF-8';
845         return $tmp;
846     };
847
848 =head1 Defining Encodings
849
850 To define a new encoding, use:
851
852     use Encode qw(define_encoding);
853     define_encoding($object, CANONICAL_NAME [, alias...]);
854
855 I<CANONICAL_NAME> will be associated with I<$object>.  The object
856 should provide the interface described in L<Encode::Encoding>.
857 If more than two arguments are provided, additional
858 arguments are considered aliases for I<$object>.
859
860 See L<Encode::Encoding> for details.
861
862 =head1 The UTF8 flag
863
864 Before the introduction of Unicode support in Perl, The C<eq> operator
865 just compared the strings represented by two scalars. Beginning with
866 Perl 5.8, C<eq> compares two strings with simultaneous consideration of
867 I<the UTF8 flag>. To explain why we made it so, I quote from page 402 of
868 I<Programming Perl, 3rd ed.>
869
870 =over 2
871
872 =item Goal #1:
873
874 Old byte-oriented programs should not spontaneously break on the old
875 byte-oriented data they used to work on.
876
877 =item Goal #2:
878
879 Old byte-oriented programs should magically start working on the new
880 character-oriented data when appropriate.
881
882 =item Goal #3:
883
884 Programs should run just as fast in the new character-oriented mode
885 as in the old byte-oriented mode.
886
887 =item Goal #4:
888
889 Perl should remain one language, rather than forking into a
890 byte-oriented Perl and a character-oriented Perl.
891
892 =back
893
894 When I<Programming Perl, 3rd ed.> was written, not even Perl 5.6.0 had been
895 born yet, many features documented in the book remained unimplemented for a
896 long time.  Perl 5.8 corrected much of this, and the introduction of the
897 UTF8 flag is one of them.  You can think of there being two fundamentally
898 different kinds of strings and string-operations in Perl: one a
899 byte-oriented mode  for when the internal UTF8 flag is off, and the other a
900 character-oriented mode for when the internal UTF8 flag is on.
901
902 Here is how C<Encode> handles the UTF8 flag.
903
904 =over 2
905
906 =item *
907
908 When you I<encode>, the resulting UTF8 flag is always B<off>.
909
910 =item *
911
912 When you I<decode>, the resulting UTF8 flag is B<on>--I<unless> you can
913 unambiguously represent data.  Here is what we mean by "unambiguously".
914 After C<$utf8 = decode("foo", $octet)>,
915
916   When $octet is...   The UTF8 flag in $utf8 is
917   ---------------------------------------------
918   In ASCII only (or EBCDIC only)            OFF
919   In ISO-8859-1                              ON
920   In any other Encoding                      ON
921   ---------------------------------------------
922
923 As you see, there is one exception: in ASCII.  That way you can assume
924 Goal #1.  And with C<Encode>, Goal #2 is assumed but you still have to be
925 careful in the cases mentioned in the B<CAVEAT> paragraphs above.
926
927 This UTF8 flag is not visible in Perl scripts, exactly for the same reason
928 you cannot (or rather, you I<don't have to>) see whether a scalar contains
929 a string, an integer, or a floating-point number.   But you can still peek
930 and poke these if you will.  See the next section.
931
932 =back
933
934 =head2 Messing with Perl's Internals
935
936 The following API uses parts of Perl's internals in the current
937 implementation.  As such, they are efficient but may change in a future
938 release.
939
940 =head3 is_utf8
941
942   is_utf8(STRING [, CHECK])
943
944 [INTERNAL] Tests whether the UTF8 flag is turned on in the I<STRING>.
945 If I<CHECK> is true, also checks whether I<STRING> contains well-formed
946 UTF-8.  Returns true if successful, false otherwise.
947
948 As of Perl 5.8.1, L<utf8> also has the C<utf8::is_utf8> function.
949
950 =head3 _utf8_on
951
952   _utf8_on(STRING)
953
954 [INTERNAL] Turns the I<STRING>'s internal UTF8 flag B<on>.  The I<STRING>
955 is I<not> checked for containing only well-formed UTF-8.  Do not use this
956 unless you I<know with absolute certainty> that the STRING holds only
957 well-formed UTF-8.  Returns the previous state of the UTF8 flag (so please
958 don't treat the return value as indicating success or failure), or C<undef>
959 if I<STRING> is not a string.
960
961 B<NOTE>: For security reasons, this function does not work on tainted values.
962
963 =head3 _utf8_off
964
965   _utf8_off(STRING)
966
967 [INTERNAL] Turns the I<STRING>'s internal UTF8 flag B<off>.  Do not use
968 frivolously.  Returns the previous state of the UTF8 flag, or C<undef> if
969 I<STRING> is not a string.  Do not treat the return value as indicative of
970 success or failure, because that isn't what it means: it is only the
971 previous setting.
972
973 B<NOTE>: For security reasons, this function does not work on tainted values.
974
975 =head1 UTF-8 vs. utf8 vs. UTF8
976
977   ....We now view strings not as sequences of bytes, but as sequences
978   of numbers in the range 0 .. 2**32-1 (or in the case of 64-bit
979   computers, 0 .. 2**64-1) -- Programming Perl, 3rd ed.
980
981 That has historically been Perl's notion of UTF-8, as that is how UTF-8 was
982 first conceived by Ken Thompson when he invented it. However, thanks to
983 later revisions to the applicable standards, official UTF-8 is now rather
984 stricter than that. For example, its range is much narrower (0 .. 0x10_FFFF
985 to cover only 21 bits instead of 32 or 64 bits) and some sequences
986 are not allowed, like those used in surrogate pairs, the 31 non-character
987 code points 0xFDD0 .. 0xFDEF, the last two code points in I<any> plane
988 (0xI<XX>_FFFE and 0xI<XX>_FFFF), all non-shortest encodings, etc.
989
990 The former default in which Perl would always use a loose interpretation of
991 UTF-8 has now been overruled:
992
993   From: Larry Wall <larry@wall.org>
994   Date: December 04, 2004 11:51:58 JST
995   To: perl-unicode@perl.org
996   Subject: Re: Make Encode.pm support the real UTF-8
997   Message-Id: <20041204025158.GA28754@wall.org>
998
999   On Fri, Dec 03, 2004 at 10:12:12PM +0000, Tim Bunce wrote:
1000   : I've no problem with 'utf8' being perl's unrestricted uft8 encoding,
1001   : but "UTF-8" is the name of the standard and should give the
1002   : corresponding behaviour.
1003
1004   For what it's worth, that's how I've always kept them straight in my
1005   head.
1006
1007   Also for what it's worth, Perl 6 will mostly default to strict but
1008   make it easy to switch back to lax.
1009
1010   Larry
1011
1012 Got that?  As of Perl 5.8.7, B<"UTF-8"> means UTF-8 in its current
1013 sense, which is conservative and strict and security-conscious, whereas
1014 B<"utf8"> means UTF-8 in its former sense, which was liberal and loose and
1015 lax.  C<Encode> version 2.10 or later thus groks this subtle but critically
1016 important distinction between C<"UTF-8"> and C<"utf8">.
1017
1018   encode("utf8",  "\x{FFFF_FFFF}", 1); # okay
1019   encode("UTF-8", "\x{FFFF_FFFF}", 1); # croaks
1020
1021 In the C<Encode> module, C<"UTF-8"> is actually a canonical name for
1022 C<"utf-8-strict">.  That hyphen between the C<"UTF"> and the C<"8"> is
1023 critical; without it, C<Encode> goes "liberal" and (perhaps overly-)permissive:
1024
1025   find_encoding("UTF-8")->name # is 'utf-8-strict'
1026   find_encoding("utf-8")->name # ditto. names are case insensitive
1027   find_encoding("utf_8")->name # ditto. "_" are treated as "-"
1028   find_encoding("UTF8")->name  # is 'utf8'.
1029
1030 Perl's internal UTF8 flag is called "UTF8", without a hyphen. It indicates
1031 whether a string is internally encoded as "utf8", also without a hyphen.
1032
1033 =head1 SEE ALSO
1034
1035 L<Encode::Encoding>,
1036 L<Encode::Supported>,
1037 L<Encode::PerlIO>,
1038 L<encoding>,
1039 L<perlebcdic>,
1040 L<perlfunc/open>,
1041 L<perlunicode>, L<perluniintro>, L<perlunifaq>, L<perlunitut>
1042 L<utf8>,
1043 the Perl Unicode Mailing List L<http://lists.perl.org/list/perl-unicode.html>
1044
1045 =head1 MAINTAINER
1046
1047 This project was originated by the late Nick Ing-Simmons and later
1048 maintained by Dan Kogai I<< <dankogai@cpan.org> >>.  See AUTHORS
1049 for a full list of people involved.  For any questions, send mail to
1050 I<< <perl-unicode@perl.org> >> so that we can all share.
1051
1052 While Dan Kogai retains the copyright as a maintainer, credit
1053 should go to all those involved.  See AUTHORS for a list of those
1054 who submitted code to the project.
1055
1056 =head1 COPYRIGHT
1057
1058 Copyright 2002-2014 Dan Kogai I<< <dankogai@cpan.org> >>.
1059
1060 This library is free software; you can redistribute it and/or modify
1061 it under the same terms as Perl itself.
1062
1063 =cut