consting-eleventy.patch: More consts, plus actual bug fix
[p5sagit/p5-mst-13.2.git] / ext / Encode / Encode.pm
CommitLineData
10c5ecbb 1#
78589665 2# $Id: Encode.pm,v 2.9 2004/12/03 19:16:40 dankogai Exp $
10c5ecbb 3#
2c674647 4package Encode;
51ef4e11 5use strict;
7f0d54d7 6# our $VERSION = do { my @r = (q$Revision: 2.9 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
b162af07 7our $VERSION = '2.0902_01';
8f139f4c 8sub DEBUG () { 0 }
6d1c0808 9use XSLoader ();
10c5ecbb 10XSLoader::load(__PACKAGE__, $VERSION);
2c674647 11
2c674647 12require Exporter;
7e19fb92 13use base qw/Exporter/;
2c674647 14
4411f3b6 15# Public, encouraged API is exported by default
85982a32 16
17our @EXPORT = qw(
18 decode decode_utf8 encode encode_utf8
a0d8a30e 19 encodings find_encoding clone_encoding
4411f3b6 20);
21
b7a5c9de 22our @FB_FLAGS = qw(DIE_ON_ERR WARN_ON_ERR RETURN_ON_ERR LEAVE_SRC
af1f55d9 23 PERLQQ HTMLCREF XMLCREF);
b7a5c9de 24our @FB_CONSTS = qw(FB_DEFAULT FB_CROAK FB_QUIET FB_WARN
af1f55d9 25 FB_PERLQQ FB_HTMLCREF FB_XMLCREF);
85982a32 26
51ef4e11 27our @EXPORT_OK =
6d1c0808 28 (
85982a32 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
6d1c0808 36our %EXPORT_TAGS =
85982a32 37 (
38 all => [ @EXPORT, @EXPORT_OK ],
39 fallbacks => [ @FB_CONSTS ],
40 fallback_all => [ @FB_CONSTS, @FB_FLAGS ],
41 );
42
4411f3b6 43# Documentation moved after __END__ for speed - NI-S
2c674647 44
a63c962f 45our $ON_EBCDIC = (ord("A") == 193);
f2a2953c 46
5d030b67 47use Encode::Alias;
48
5129552c 49# Make a %Encoding package variable to allow a certain amount of cheating
50our %Encoding;
aae85ceb 51our %ExtModule;
52require Encode::Config;
53eval { require Encode::ConfigLocal };
5129552c 54
656753f8 55sub encodings
56{
5129552c 57 my $class = shift;
fc17bd48 58 my %enc;
59 if (@_ and $_[0] eq ":all"){
60 %enc = ( %Encoding, %ExtModule );
61 }else{
62 %enc = %Encoding;
63 for my $mod (map {m/::/o ? $_ : "Encode::$_" } @_){
8f139f4c 64 DEBUG and warn $mod;
fc17bd48 65 for my $enc (keys %ExtModule){
66 $ExtModule{$enc} eq $mod and $enc{$enc} = $mod;
67 }
68 }
5129552c 69 }
70 return
ce912cd4 71 sort { lc $a cmp lc $b }
fc17bd48 72 grep {!/^(?:Internal|Unicode|Guess)$/o} keys %enc;
51ef4e11 73}
74
85982a32 75sub perlio_ok{
0ab8f81e 76 my $obj = ref($_[0]) ? $_[0] : find_encoding($_[0]);
011b2d2f 77 $obj->can("perlio_ok") and return $obj->perlio_ok();
0ab8f81e 78 return 0; # safety net
85982a32 79}
80
51ef4e11 81sub define_encoding
82{
18586f54 83 my $obj = shift;
84 my $name = shift;
5129552c 85 $Encoding{$name} = $obj;
18586f54 86 my $lc = lc($name);
87 define_alias($lc => $obj) unless $lc eq $name;
10c5ecbb 88 while (@_){
18586f54 89 my $alias = shift;
10c5ecbb 90 define_alias($alias, $obj);
18586f54 91 }
92 return $obj;
656753f8 93}
94
656753f8 95sub getEncoding
96{
10c5ecbb 97 my ($class, $name, $skip_external) = @_;
98
a0d8a30e 99 ref($name) && $name->can('renew') and return $name;
10c5ecbb 100 exists $Encoding{$name} and return $Encoding{$name};
18586f54 101 my $lc = lc $name;
10c5ecbb 102 exists $Encoding{$lc} and return $Encoding{$lc};
c50d192e 103
5129552c 104 my $oc = $class->find_alias($name);
10c5ecbb 105 defined($oc) and return $oc;
106 $lc ne $name and $oc = $class->find_alias($lc);
107 defined($oc) and return $oc;
c50d192e 108
c731e18e 109 unless ($skip_external)
d1ed7747 110 {
c731e18e 111 if (my $mod = $ExtModule{$name} || $ExtModule{$lc}){
112 $mod =~ s,::,/,g ; $mod .= '.pm';
113 eval{ require $mod; };
10c5ecbb 114 exists $Encoding{$name} and return $Encoding{$name};
c731e18e 115 }
d1ed7747 116 }
18586f54 117 return;
656753f8 118}
119
a0d8a30e 120sub find_encoding($;$)
4411f3b6 121{
10c5ecbb 122 my ($name, $skip_external) = @_;
dd9703c9 123 return __PACKAGE__->getEncoding($name,$skip_external);
4411f3b6 124}
125
a0d8a30e 126sub resolve_alias($){
fcb875d4 127 my $obj = find_encoding(shift);
128 defined $obj and return $obj->name;
129 return;
130}
131
a0d8a30e 132sub clone_encoding($){
133 my $obj = find_encoding(shift);
134 ref $obj or return;
135 eval { require Storable };
136 $@ and return;
137 return Storable::dclone($obj);
138}
139
b2704119 140sub encode($$;$)
4411f3b6 141{
e8c86ba6 142 my ($name, $string, $check) = @_;
0f7c507f 143 return undef unless defined $string;
78589665 144 $string .= '' if ref $string; # stringify;
b2704119 145 $check ||=0;
18586f54 146 my $enc = find_encoding($name);
10c5ecbb 147 unless(defined $enc){
148 require Carp;
149 Carp::croak("Unknown encoding '$name'");
150 }
18586f54 151 my $octets = $enc->encode($string,$check);
7f0d54d7 152 $_[1] = $string if $check and !($check & LEAVE_SRC());
18586f54 153 return $octets;
4411f3b6 154}
155
b2704119 156sub decode($$;$)
4411f3b6 157{
18586f54 158 my ($name,$octets,$check) = @_;
0f7c507f 159 return undef unless defined $octets;
78589665 160 $octets .= '' if ref $octets;
b2704119 161 $check ||=0;
18586f54 162 my $enc = find_encoding($name);
10c5ecbb 163 unless(defined $enc){
164 require Carp;
165 Carp::croak("Unknown encoding '$name'");
166 }
18586f54 167 my $string = $enc->decode($octets,$check);
7f0d54d7 168 $_[1] = $octets if $check and !($check & LEAVE_SRC());
18586f54 169 return $string;
4411f3b6 170}
171
b2704119 172sub from_to($$$;$)
4411f3b6 173{
18586f54 174 my ($string,$from,$to,$check) = @_;
0f7c507f 175 return undef unless defined $string;
b2704119 176 $check ||=0;
18586f54 177 my $f = find_encoding($from);
10c5ecbb 178 unless (defined $f){
179 require Carp;
180 Carp::croak("Unknown encoding '$from'");
181 }
18586f54 182 my $t = find_encoding($to);
10c5ecbb 183 unless (defined $t){
184 require Carp;
185 Carp::croak("Unknown encoding '$to'");
186 }
18586f54 187 my $uni = $f->decode($string,$check);
188 return undef if ($check && length($string));
a999c27c 189 $string = $t->encode($uni,$check);
18586f54 190 return undef if ($check && length($uni));
3ef515df 191 return defined($_[0] = $string) ? length($string) : undef ;
4411f3b6 192}
193
b2704119 194sub encode_utf8($)
4411f3b6 195{
18586f54 196 my ($str) = @_;
c731e18e 197 utf8::encode($str);
18586f54 198 return $str;
4411f3b6 199}
200
c2cbba7d 201sub decode_utf8($;$)
4411f3b6 202{
c2cbba7d 203 my ($str, $check) = @_;
204 if ($check){
205 return decode("utf8", $str, $check);
206 }else{
207 return undef unless utf8::decode($str);
208 return $str;
209 }
5ad8ef52 210}
211
b536bf57 212predefine_encodings(1);
f2a2953c 213
214#
215# This is to restore %Encoding if really needed;
216#
10c5ecbb 217
f2a2953c 218sub predefine_encodings{
10c5ecbb 219 use Encode::Encoding;
b536bf57 220 no warnings 'redefine';
221 my $use_xs = shift;
6d1c0808 222 if ($ON_EBCDIC) {
f2a2953c 223 # was in Encode::UTF_EBCDIC
224 package Encode::UTF_EBCDIC;
10c5ecbb 225 push @Encode::UTF_EBCDIC::ISA, 'Encode::Encoding';
f2a2953c 226 *decode = sub{
227 my ($obj,$str,$chk) = @_;
228 my $res = '';
229 for (my $i = 0; $i < length($str); $i++) {
6d1c0808 230 $res .=
f2a2953c 231 chr(utf8::unicode_to_native(ord(substr($str,$i,1))));
232 }
233 $_[1] = '' if $chk;
234 return $res;
235 };
236 *encode = sub{
237 my ($obj,$str,$chk) = @_;
238 my $res = '';
239 for (my $i = 0; $i < length($str); $i++) {
6d1c0808 240 $res .=
f2a2953c 241 chr(utf8::native_to_unicode(ord(substr($str,$i,1))));
242 }
243 $_[1] = '' if $chk;
244 return $res;
245 };
6d1c0808 246 $Encode::Encoding{Unicode} =
c731e18e 247 bless {Name => "UTF_EBCDIC"} => "Encode::UTF_EBCDIC";
6d1c0808 248 } else {
f2a2953c 249 package Encode::Internal;
10c5ecbb 250 push @Encode::Internal::ISA, 'Encode::Encoding';
f2a2953c 251 *decode = sub{
252 my ($obj,$str,$chk) = @_;
253 utf8::upgrade($str);
254 $_[1] = '' if $chk;
255 return $str;
256 };
257 *encode = \&decode;
6d1c0808 258 $Encode::Encoding{Unicode} =
c731e18e 259 bless {Name => "Internal"} => "Encode::Internal";
f2a2953c 260 }
261
262 {
263 # was in Encode::utf8
264 package Encode::utf8;
10c5ecbb 265 push @Encode::utf8::ISA, 'Encode::Encoding';
b536bf57 266 #
267 if ($use_xs){
8f139f4c 268 Encode::DEBUG and warn __PACKAGE__, " XS on";
b536bf57 269 *decode = \&decode_xs;
270 *encode = \&encode_xs;
271 }else{
8f139f4c 272 Encode::DEBUG and warn __PACKAGE__, " XS off";
b536bf57 273 *decode = sub{
274 my ($obj,$octets,$chk) = @_;
275 my $str = Encode::decode_utf8($octets);
276 if (defined $str) {
277 $_[1] = '' if $chk;
278 return $str;
279 }
280 return undef;
281 };
282 *encode = sub {
283 my ($obj,$string,$chk) = @_;
284 my $octets = Encode::encode_utf8($string);
285 $_[1] = '' if $chk;
286 return $octets;
287 };
288 }
220e2d4e 289 *cat_decode = sub{ # ($obj, $dst, $src, $pos, $trm, $chk)
290 my ($obj, undef, undef, $pos, $trm) = @_; # currently ignores $chk
291 my ($rdst, $rsrc, $rpos) = \@_[1,2,3];
292 use bytes;
293 if ((my $npos = index($$rsrc, $trm, $pos)) >= 0) {
294 $$rdst .= substr($$rsrc, $pos, $npos - $pos + length($trm));
295 $$rpos = $npos + length($trm);
296 return 1;
297 }
298 $$rdst .= substr($$rsrc, $pos);
299 $$rpos = length($$rsrc);
300 return '';
301 };
b7a5c9de 302 $Encode::Encoding{utf8} =
c731e18e 303 bless {Name => "utf8"} => "Encode::utf8";
7f0d54d7 304 $Encode::Encoding{"utf-8-strict"} =
305 bless {Name => "utf-8-strict", strict_utf8 => 1 } => "Encode::utf8";
f2a2953c 306 }
f2a2953c 307}
308
656753f8 3091;
310
2a936312 311__END__
312
4411f3b6 313=head1 NAME
314
315Encode - character encodings
316
317=head1 SYNOPSIS
318
319 use Encode;
320
67d7b5ef 321=head2 Table of Contents
322
0ab8f81e 323Encode consists of a collection of modules whose details are too big
67d7b5ef 324to fit in one document. This POD itself explains the top-level APIs
6d1c0808 325and general topics at a glance. For other topics and more details,
0ab8f81e 326see the PODs below:
67d7b5ef 327
328 Name Description
329 --------------------------------------------------------
6d1c0808 330 Encode::Alias Alias definitions to encodings
67d7b5ef 331 Encode::Encoding Encode Implementation Base Class
332 Encode::Supported List of Supported Encodings
333 Encode::CN Simplified Chinese Encodings
334 Encode::JP Japanese Encodings
335 Encode::KR Korean Encodings
336 Encode::TW Traditional Chinese Encodings
337 --------------------------------------------------------
338
4411f3b6 339=head1 DESCRIPTION
340
47bfe92f 341The C<Encode> module provides the interfaces between Perl's strings
67d7b5ef 342and the rest of the system. Perl strings are sequences of
343B<characters>.
344
345The repertoire of characters that Perl can represent is at least that
346defined by the Unicode Consortium. On most platforms the ordinal
347values of the characters (as returned by C<ord(ch)>) is the "Unicode
348codepoint" for the character (the exceptions are those platforms where
349the legacy encoding is some variant of EBCDIC rather than a super-set
350of ASCII - see L<perlebcdic>).
351
0ab8f81e 352Traditionally, computer data has been moved around in 8-bit chunks
67d7b5ef 353often called "bytes". These chunks are also known as "octets" in
354networking standards. Perl is widely used to manipulate data of many
355types - not only strings of characters representing human or computer
0ab8f81e 356languages but also "binary" data being the machine's representation of
67d7b5ef 357numbers, pixels in an image - or just about anything.
358
0ab8f81e 359When Perl is processing "binary data", the programmer wants Perl to
67d7b5ef 360process "sequences of bytes". This is not a problem for Perl - as a
0ab8f81e 361byte has 256 possible values, it easily fits in Perl's much larger
67d7b5ef 362"logical character".
363
364=head2 TERMINOLOGY
4411f3b6 365
7e19fb92 366=over 2
21938dfa 367
67d7b5ef 368=item *
369
370I<character>: a character in the range 0..(2**32-1) (or more).
371(What Perl's strings are made of.)
372
373=item *
374
375I<byte>: a character in the range 0..255
376(A special case of a Perl character.)
377
378=item *
379
380I<octet>: 8 bits of data, with ordinal values 0..255
0ab8f81e 381(Term for bytes passed to or from a non-Perl context, e.g. a disk file.)
67d7b5ef 382
383=back
4411f3b6 384
67d7b5ef 385=head1 PERL ENCODING API
4411f3b6 386
7e19fb92 387=over 2
4411f3b6 388
b7a5c9de 389=item $octets = encode(ENCODING, $string [, CHECK])
4411f3b6 390
0ab8f81e 391Encodes a string from Perl's internal form into I<ENCODING> and returns
67d7b5ef 392a sequence of octets. ENCODING can be either a canonical name or
0ab8f81e 393an alias. For encoding names and aliases, see L</"Defining Aliases">.
394For CHECK, see L</"Handling Malformed Data">.
4411f3b6 395
b7a5c9de 396For example, to convert a string from Perl's internal format to
6d1c0808 397iso-8859-1 (also known as Latin1),
681a7c68 398
b7a5c9de 399 $octets = encode("iso-8859-1", $string);
7e19fb92 400
b7a5c9de 401B<CAVEAT>: When you run C<$octets = encode("utf8", $string)>, then $octets
402B<may not be equal to> $string. Though they both contain the same data, the utf8 flag
7e19fb92 403for $octets is B<always> off. When you encode anything, utf8 flag of
404the result is always off, even when it contains completely valid utf8
405string. See L</"The UTF-8 flag"> below.
681a7c68 406
7f0d54d7 407If the $string is C<undef> then C<undef> is returned.
4089adc4 408
b7a5c9de 409=item $string = decode(ENCODING, $octets [, CHECK])
4411f3b6 410
0ab8f81e 411Decodes a sequence of octets assumed to be in I<ENCODING> into Perl's
412internal form and returns the resulting string. As in encode(),
413ENCODING can be either a canonical name or an alias. For encoding names
414and aliases, see L</"Defining Aliases">. For CHECK, see
47bfe92f 415L</"Handling Malformed Data">.
416
b7a5c9de 417For example, to convert ISO-8859-1 data to a string in Perl's internal format:
681a7c68 418
b7a5c9de 419 $string = decode("iso-8859-1", $octets);
681a7c68 420
b7a5c9de 421B<CAVEAT>: When you run C<$string = decode("utf8", $octets)>, then $string
422B<may not be equal to> $octets. Though they both contain the same data,
423the utf8 flag for $string is on unless $octets entirely consists of
7e19fb92 424ASCII data (or EBCDIC on EBCDIC machines). See L</"The UTF-8 flag">
425below.
47bfe92f 426
7f0d54d7 427If the $string is C<undef> then C<undef> is returned.
4089adc4 428
b7a5c9de 429=item [$length =] from_to($octets, FROM_ENC, TO_ENC [, CHECK])
7e19fb92 430
b7a5c9de 431Converts B<in-place> data between two encodings. The data in $octets
432must be encoded as octets and not as characters in Perl's internal
f9d05ba3 433format. For example, to convert ISO-8859-1 data to Microsoft's CP1250
434encoding:
2b106fbe 435
b7a5c9de 436 from_to($octets, "iso-8859-1", "cp1250");
2b106fbe 437
438and to convert it back:
439
b7a5c9de 440 from_to($octets, "cp1250", "iso-8859-1");
4411f3b6 441
ab97ca19 442Note that because the conversion happens in place, the data to be
0ab8f81e 443converted cannot be a string constant; it must be a scalar variable.
ab97ca19 444
f9d05ba3 445from_to() returns the length of the converted string in octets on
446success, I<undef> on error.
3ef515df 447
b7a5c9de 448B<CAVEAT>: The following operations look the same but are not quite so;
7e19fb92 449
b7a5c9de 450 from_to($data, "iso-8859-1", "utf8"); #1
7e19fb92 451 $data = decode("iso-8859-1", $data); #2
4411f3b6 452
b7a5c9de 453Both #1 and #2 make $data consist of a completely valid UTF-8 string
7e19fb92 454but only #2 turns utf8 flag on. #1 is equivalent to
f2a2953c 455
7e19fb92 456 $data = encode("utf8", decode("iso-8859-1", $data));
f2a2953c 457
7e19fb92 458See L</"The UTF-8 flag"> below.
f2a2953c 459
460=item $octets = encode_utf8($string);
461
7e19fb92 462Equivalent to C<$octets = encode("utf8", $string);> The characters
b7a5c9de 463that comprise $string are encoded in Perl's internal format and the
464result is returned as a sequence of octets. All possible
7e19fb92 465characters have a UTF-8 representation so this function cannot fail.
466
f2a2953c 467
468=item $string = decode_utf8($octets [, CHECK]);
469
7e19fb92 470equivalent to C<$string = decode("utf8", $octets [, CHECK])>.
b7a5c9de 471The sequence of octets represented by
7e19fb92 472$octets is decoded from UTF-8 into a sequence of logical
473characters. Not all sequences of octets form valid UTF-8 encodings, so
474it is possible for this call to fail. For CHECK, see
475L</"Handling Malformed Data">.
f2a2953c 476
477=back
478
51ef4e11 479=head2 Listing available encodings
480
5129552c 481 use Encode;
482 @list = Encode->encodings();
483
484Returns a list of the canonical names of the available encodings that
485are loaded. To get a list of all available encodings including the
486ones that are not loaded yet, say
487
488 @all_encodings = Encode->encodings(":all");
489
0ab8f81e 490Or you can give the name of a specific module.
5129552c 491
c731e18e 492 @with_jp = Encode->encodings("Encode::JP");
493
494When "::" is not in the name, "Encode::" is assumed.
51ef4e11 495
c731e18e 496 @ebcdic = Encode->encodings("EBCDIC");
5d030b67 497
0ab8f81e 498To find out in detail which encodings are supported by this package,
5d030b67 499see L<Encode::Supported>.
51ef4e11 500
501=head2 Defining Aliases
502
0ab8f81e 503To add a new alias to a given encoding, use:
67d7b5ef 504
5129552c 505 use Encode;
506 use Encode::Alias;
a63c962f 507 define_alias(newName => ENCODING);
51ef4e11 508
3ef515df 509After that, newName can be used as an alias for ENCODING.
f2a2953c 510ENCODING may be either the name of an encoding or an
511I<encoding object>
51ef4e11 512
fcb875d4 513But before you do so, make sure the alias is nonexistent with
514C<resolve_alias()>, which returns the canonical name thereof.
515i.e.
516
517 Encode::resolve_alias("latin1") eq "iso-8859-1" # true
518 Encode::resolve_alias("iso-8859-12") # false; nonexistent
519 Encode::resolve_alias($name) eq $name # true if $name is canonical
520
0ab8f81e 521resolve_alias() does not need C<use Encode::Alias>; it can be
522exported via C<use Encode qw(resolve_alias)>.
fcb875d4 523
0ab8f81e 524See L<Encode::Alias> for details.
51ef4e11 525
85982a32 526=head1 Encoding via PerlIO
4411f3b6 527
b7a5c9de 528If your perl supports I<PerlIO> (which is the default), you can use a PerlIO layer to decode
0ab8f81e 529and encode directly via a filehandle. The following two examples
530are totally identical in their functionality.
4411f3b6 531
85982a32 532 # via PerlIO
533 open my $in, "<:encoding(shiftjis)", $infile or die;
534 open my $out, ">:encoding(euc-jp)", $outfile or die;
b7a5c9de 535 while(<$in>){ print $out $_; }
8e86646e 536
85982a32 537 # via from_to
0ab8f81e 538 open my $in, "<", $infile or die;
539 open my $out, ">", $outfile or die;
b7a5c9de 540 while(<$in>){
0ab8f81e 541 from_to($_, "shiftjis", "euc-jp", 1);
b7a5c9de 542 print $out $_;
85982a32 543 }
4411f3b6 544
b7a5c9de 545Unfortunately, it may be that encodings are PerlIO-savvy. You can check
0ab8f81e 546if your encoding is supported by PerlIO by calling the C<perlio_ok>
547method.
548
549 Encode::perlio_ok("hz"); # False
550 find_encoding("euc-cn")->perlio_ok; # True where PerlIO is available
551
552 use Encode qw(perlio_ok); # exported upon request
553 perlio_ok("euc-jp")
4411f3b6 554
0ab8f81e 555Fortunately, all encodings that come with Encode core are PerlIO-savvy
f9d05ba3 556except for hz and ISO-2022-kr. For gory details, see
557L<Encode::Encoding> and L<Encode::PerlIO>.
4411f3b6 558
85982a32 559=head1 Handling Malformed Data
4411f3b6 560
f9d05ba3 561The optional I<CHECK> argument is used as follows. When you omit it,
562Encode::FB_DEFAULT ( == 0 ) is assumed.
563
564=over 2
565
566=item B<NOTE:> Not all encoding suppport this feature
567
568Some encodings ignore I<CHECK> argument. For example,
569L<Encode::Unicode> ignores I<CHECK> and it always croaks on error.
570
571=back
572
573Now here is the list of I<CHECK> values available
47bfe92f 574
151b5d36 575=over 2
576
85982a32 577=item I<CHECK> = Encode::FB_DEFAULT ( == 0)
47bfe92f 578
f9d05ba3 579If I<CHECK> is 0, (en|de)code will put a I<substitution character> in
78589665 580place of a malformed character. When you encode, E<lt>subcharE<gt>
581will be used. When you decode the code point C<0xFFFD> is used. If
582the data is supposed to be UTF-8, an optional lexical warning
583(category utf8) is given.
e9692b5b 584
7e19fb92 585=item I<CHECK> = Encode::FB_CROAK ( == 1)
e9692b5b 586
b7a5c9de 587If I<CHECK> is 1, methods will die on error immediately with an error
0ab8f81e 588message. Therefore, when I<CHECK> is set to 1, you should trap the
f9d05ba3 589error with eval{} unless you really want to let it die.
47bfe92f 590
85982a32 591=item I<CHECK> = Encode::FB_QUIET
47bfe92f 592
85982a32 593If I<CHECK> is set to Encode::FB_QUIET, (en|de)code will immediately
f9d05ba3 594return the portion of the data that has been processed so far when an
595error occurs. The data argument will be overwritten with everything
596after that point (that is, the unprocessed part of data). This is
597handy when you have to call decode repeatedly in the case where your
598source data may contain partial multi-byte character sequences,
599(i.e. you are reading with a fixed-width buffer). Here is a sample
600code that does exactly this:
4411f3b6 601
78589665 602 my $buffer = ''; my $string = '';
603 while(read $fh, $buffer, 256, length($buffer)){
604 $string .= decode($encoding, $buffer, Encode::FB_QUIET);
605 # $buffer now contains the unprocessed partial character
85982a32 606 }
1768d7eb 607
85982a32 608=item I<CHECK> = Encode::FB_WARN
67d7b5ef 609
0ab8f81e 610This is the same as above, except that it warns on error. Handy when
611you are debugging the mode above.
85982a32 612
613=item perlqq mode (I<CHECK> = Encode::FB_PERLQQ)
614
af1f55d9 615=item HTML charref mode (I<CHECK> = Encode::FB_HTMLCREF)
616
617=item XML charref mode (I<CHECK> = Encode::FB_XMLCREF)
618
85982a32 619For encodings that are implemented by Encode::XS, CHECK ==
620Encode::FB_PERLQQ turns (en|de)code into C<perlqq> fallback mode.
621
b7a5c9de 622When you decode, C<\xI<HH>> will be inserted for a malformed character,
623where I<HH> is the hex representation of the octet that could not be
624decoded to utf8. And when you encode, C<\x{I<HHHH>}> will be inserted,
625where I<HHHH> is the Unicode ID of the character that cannot be found
0ab8f81e 626in the character repertoire of the encoding.
85982a32 627
af1f55d9 628HTML/XML character reference modes are about the same, in place of
78589665 629C<\x{I<HHHH>}>, HTML uses C<&#I<NNN>;> where I<NNN> is a decimal number and
630XML uses C<&#xI<HHHH>;> where I<HHHH> is the hexadecimal number.
af1f55d9 631
7f0d54d7 632In Encode 2.10 or later, C<LEAVE_SRC> is also implied.
633
85982a32 634=item The bitmask
635
0ab8f81e 636These modes are actually set via a bitmask. Here is how the FB_XX
637constants are laid out. You can import the FB_XX constants via
638C<use Encode qw(:fallbacks)>; you can import the generic bitmask
639constants via C<use Encode qw(:fallback_all)>.
85982a32 640
b0b300a3 641 FB_DEFAULT FB_CROAK FB_QUIET FB_WARN FB_PERLQQ
642 DIE_ON_ERR 0x0001 X
4089adc4 643 WARN_ON_ERR 0x0002 X
b0b300a3 644 RETURN_ON_ERR 0x0004 X X
7f0d54d7 645 LEAVE_SRC 0x0008 X
b0b300a3 646 PERLQQ 0x0100 X
b7a5c9de 647 HTMLCREF 0x0200
648 XMLCREF 0x0400
67d7b5ef 649
151b5d36 650=back
651
0ab8f81e 652=head2 Unimplemented fallback schemes
67d7b5ef 653
0ab8f81e 654In the future, you will be able to use a code reference to a callback
f2a2953c 655function for the value of I<CHECK> but its API is still undecided.
67d7b5ef 656
982a4085 657The fallback scheme does not work on EBCDIC platforms.
658
67d7b5ef 659=head1 Defining Encodings
660
661To define a new encoding, use:
662
b7a5c9de 663 use Encode qw(define_encoding);
67d7b5ef 664 define_encoding($object, 'canonicalName' [, alias...]);
665
666I<canonicalName> will be associated with I<$object>. The object
0ab8f81e 667should provide the interface described in L<Encode::Encoding>.
67d7b5ef 668If more than two arguments are provided then additional
b7a5c9de 669arguments are taken as aliases for I<$object>.
67d7b5ef 670
f2a2953c 671See L<Encode::Encoding> for more details.
672
7e19fb92 673=head1 The UTF-8 flag
674
675Before the introduction of utf8 support in perl, The C<eq> operator
b7a5c9de 676just compared the strings represented by two scalars. Beginning with
677perl 5.8, C<eq> compares two strings with simultaneous consideration
678of I<the utf8 flag>. To explain why we made it so, I will quote page
679402 of C<Programming Perl, 3rd ed.>
7e19fb92 680
681=over 2
682
683=item Goal #1:
684
685Old byte-oriented programs should not spontaneously break on the old
686byte-oriented data they used to work on.
687
688=item Goal #2:
689
690Old byte-oriented programs should magically start working on the new
691character-oriented data when appropriate.
692
693=item Goal #3:
694
695Programs should run just as fast in the new character-oriented mode
696as in the old byte-oriented mode.
697
698=item Goal #4:
699
700Perl should remain one language, rather than forking into a
701byte-oriented Perl and a character-oriented Perl.
702
703=back
704
705Back when C<Programming Perl, 3rd ed.> was written, not even Perl 5.6.0
706was born and many features documented in the book remained
b7a5c9de 707unimplemented for a long time. Perl 5.8 corrected this and the introduction
708of the UTF-8 flag is one of them. You can think of this perl notion as of a
709byte-oriented mode (utf8 flag off) and a character-oriented mode (utf8
7e19fb92 710flag on).
711
712Here is how Encode takes care of the utf8 flag.
713
4bdf5738 714=over 2
7e19fb92 715
716=item *
717
718When you encode, the resulting utf8 flag is always off.
719
151b5d36 720=item *
7e19fb92 721
b7a5c9de 722When you decode, the resulting utf8 flag is on unless you can
7e19fb92 723unambiguously represent data. Here is the definition of
724dis-ambiguity.
725
b7a5c9de 726After C<$utf8 = decode('foo', $octet);>,
7e19fb92 727
728 When $octet is... The utf8 flag in $utf8 is
729 ---------------------------------------------
730 In ASCII only (or EBCDIC only) OFF
731 In ISO-8859-1 ON
732 In any other Encoding ON
733 ---------------------------------------------
734
735As you see, there is one exception, In ASCII. That way you can assue
736Goal #1. And with Encode Goal #2 is assumed but you still have to be
737careful in such cases mentioned in B<CAVEAT> paragraphs.
738
739This utf8 flag is not visible in perl scripts, exactly for the same
740reason you cannot (or you I<don't have to>) see if a scalar contains a
741string, integer, or floating point number. But you can still peek
742and poke these if you will. See the section below.
743
744=back
745
746=head2 Messing with Perl's Internals
4411f3b6 747
47bfe92f 748The following API uses parts of Perl's internals in the current
0ab8f81e 749implementation. As such, they are efficient but may change.
4411f3b6 750
7e19fb92 751=over 2
4411f3b6 752
a63c962f 753=item is_utf8(STRING [, CHECK])
4411f3b6 754
0ab8f81e 755[INTERNAL] Tests whether the UTF-8 flag is turned on in the STRING.
47bfe92f 756If CHECK is true, also checks the data in STRING for being well-formed
757UTF-8. Returns true if successful, false otherwise.
4411f3b6 758
2c246b25 759As of perl 5.8.1, L<utf8> also has utf8::is_utf8().
b5ab1f6f 760
a63c962f 761=item _utf8_on(STRING)
4411f3b6 762
0ab8f81e 763[INTERNAL] Turns on the UTF-8 flag in STRING. The data in STRING is
4411f3b6 764B<not> checked for being well-formed UTF-8. Do not use unless you
765B<know> that the STRING is well-formed UTF-8. Returns the previous
0ab8f81e 766state of the UTF-8 flag (so please don't treat the return value as
767indicating success or failure), or C<undef> if STRING is not a string.
4411f3b6 768
a63c962f 769=item _utf8_off(STRING)
4411f3b6 770
0ab8f81e 771[INTERNAL] Turns off the UTF-8 flag in STRING. Do not use frivolously.
772Returns the previous state of the UTF-8 flag (so please don't treat the
773return value as indicating success or failure), or C<undef> if STRING is
4411f3b6 774not a string.
775
776=back
777
7f0d54d7 778=head1 UTF-8 vs. utf8
779
780 ....We now view strings not as sequences of bytes, but as sequences
781 of numbers in the range 0 .. 2**32-1 (or in the case of 64-bit
782 computers, 0 .. 2**64-1) -- Programming Perl, 3rd ed.
783
784That has been the perl's notion of UTF-8 but official UTF-8 is more
785strict; Its ranges is much narrower (0 .. 10FFFF), some sequences are
786not allowed (i.e. Those used in the surrogate pair, 0xFFFE, et al).
787
788Now that is overruled by Larry Wall himself.
789
790 From: Larry Wall <larry@wall.org>
791 Date: December 04, 2004 11:51:58 JST
792 To: perl-unicode@perl.org
793 Subject: Re: Make Encode.pm support the real UTF-8
794 Message-Id: <20041204025158.GA28754@wall.org>
795
796 On Fri, Dec 03, 2004 at 10:12:12PM +0000, Tim Bunce wrote:
797 : I've no problem with 'utf8' being perl's unrestricted uft8 encoding,
798 : but "UTF-8" is the name of the standard and should give the
799 : corresponding behaviour.
800
801 For what it's worth, that's how I've always kept them straight in my
802 head.
803
804 Also for what it's worth, Perl 6 will mostly default to strict but
805 make it easy to switch back to lax.
806
807 Larry
808
809Do you copy? As of Perl 5.8.7, B<UTF-8> means strict, official UTF-8
810while B<utf8> means liberal, lax, version thereof. And Encode version
8112.10 or later thus groks the difference between C<UTF-8> and C"utf8".
812
813 encode("utf8", "\x{FFFF_FFFF}", 1); # okay
814 encode("UTF-8", "\x{FFFF_FFFF}", 1); # croaks
815
816C<UTF-8> in Encode is actually a canonical name for C<utf-8-strict>.
817Yes, the hyphen between "UTF" and "8" is important. Without it Encode
818goes "liberal"
819
820 find_encoding("UTF-8")->name # is 'utf-8-strict'
821 find_encoding("utf-8")->name # ditto. names are case insensitive
822 find_encoding("utf8")->name # ditto. "_" are treated as "-"
823 find_encoding("UTF8")->name # is 'utf8'.
824
825
4411f3b6 826=head1 SEE ALSO
827
5d030b67 828L<Encode::Encoding>,
829L<Encode::Supported>,
6d1c0808 830L<Encode::PerlIO>,
5d030b67 831L<encoding>,
6d1c0808 832L<perlebcdic>,
833L<perlfunc/open>,
834L<perlunicode>,
835L<utf8>,
5d030b67 836the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>
4411f3b6 837
85982a32 838=head1 MAINTAINER
aae85ceb 839
840This project was originated by Nick Ing-Simmons and later maintained
7e19fb92 841by Dan Kogai E<lt>dankogai@dan.co.jpE<gt>. See AUTHORS for a full
842list of people involved. For any questions, use
b7a5c9de 843E<lt>perl-unicode@perl.orgE<gt> so we can all share.
aae85ceb 844
4411f3b6 845=cut