1package Encode::Guess; 2use strict; 3use warnings; 4use Encode qw(:fallbacks find_encoding); 5our $VERSION = do { my @r = ( q$Revision: 2.8 $ =~ /\d+/g ); sprintf "%d." . "%02d" x $#r, @r }; 6 7my $Canon = 'Guess'; 8use constant DEBUG => !!$ENV{PERL_ENCODE_DEBUG}; 9our %DEF_SUSPECTS = map { $_ => find_encoding($_) } qw(ascii utf8); 10my $obj = bless { 11 Name => $Canon, 12 Suspects => {%DEF_SUSPECTS}, 13} => __PACKAGE__; 14Encode::define_encoding($obj, $Canon); 15 16use parent qw(Encode::Encoding); 17sub needs_lines { 1 } 18sub perlio_ok { 0 } 19 20our @EXPORT = qw(guess_encoding); 21our $NoUTFAutoGuess = 0; 22our $UTF8_BOM = pack( "C3", 0xef, 0xbb, 0xbf ); 23 24sub import { # Exporter not used so we do it on our own 25 my $callpkg = caller; 26 for my $item (@EXPORT) { 27 no strict 'refs'; 28 *{"$callpkg\::$item"} = \&{"$item"}; 29 } 30 set_suspects(@_); 31} 32 33sub set_suspects { 34 my $class = shift; 35 my $self = ref($class) ? $class : $Encode::Encoding{$Canon}; 36 $self->{Suspects} = {%DEF_SUSPECTS}; 37 $self->add_suspects(@_); 38} 39 40sub add_suspects { 41 my $class = shift; 42 my $self = ref($class) ? $class : $Encode::Encoding{$Canon}; 43 for my $c (@_) { 44 my $e = find_encoding($c) or die "Unknown encoding: $c"; 45 $self->{Suspects}{ $e->name } = $e; 46 DEBUG and warn "Added: ", $e->name; 47 } 48} 49 50sub decode($$;$) { 51 my ( $obj, $octet, $chk ) = @_; 52 my $guessed = guess( $obj, $octet ); 53 unless ( ref($guessed) ) { 54 require Carp; 55 Carp::croak($guessed); 56 } 57 my $utf8 = $guessed->decode( $octet, $chk || 0 ); 58 $_[1] = $octet if $chk; 59 return $utf8; 60} 61 62sub guess_encoding { 63 guess( $Encode::Encoding{$Canon}, @_ ); 64} 65 66sub guess { 67 my $class = shift; 68 my $obj = ref($class) ? $class : $Encode::Encoding{$Canon}; 69 my $octet = shift; 70 71 # sanity check 72 return "Empty string, empty guess" unless defined $octet and length $octet; 73 74 # cheat 0: utf8 flag; 75 if ( Encode::is_utf8($octet) ) { 76 return find_encoding('utf8') unless $NoUTFAutoGuess; 77 Encode::_utf8_off($octet); 78 } 79 80 # cheat 1: BOM 81 use Encode::Unicode; 82 unless ($NoUTFAutoGuess) { 83 my $BOM = pack( 'C3', unpack( "C3", $octet ) ); 84 return find_encoding('utf8') 85 if ( defined $BOM and $BOM eq $UTF8_BOM ); 86 $BOM = unpack( 'N', $octet ); 87 return find_encoding('UTF-32') 88 if ( defined $BOM and ( $BOM == 0xFeFF or $BOM == 0xFFFe0000 ) ); 89 $BOM = unpack( 'n', $octet ); 90 return find_encoding('UTF-16') 91 if ( defined $BOM and ( $BOM == 0xFeFF or $BOM == 0xFFFe ) ); 92 if ( $octet =~ /\x00/o ) 93 { # if \x00 found, we assume UTF-(16|32)(BE|LE) 94 my $utf; 95 my ( $be, $le ) = ( 0, 0 ); 96 if ( $octet =~ /\x00\x00/o ) { # UTF-32(BE|LE) assumed 97 $utf = "UTF-32"; 98 for my $char ( unpack( 'N*', $octet ) ) { 99 $char & 0x0000ffff and $be++; 100 $char & 0xffff0000 and $le++; 101 } 102 } 103 else { # UTF-16(BE|LE) assumed 104 $utf = "UTF-16"; 105 for my $char ( unpack( 'n*', $octet ) ) { 106 $char & 0x00ff and $be++; 107 $char & 0xff00 and $le++; 108 } 109 } 110 DEBUG and warn "$utf, be == $be, le == $le"; 111 $be == $le 112 and return 113 "Encodings ambiguous between $utf BE and LE ($be, $le)"; 114 $utf .= ( $be > $le ) ? 'BE' : 'LE'; 115 return find_encoding($utf); 116 } 117 } 118 my %try = %{ $obj->{Suspects} }; 119 for my $c (@_) { 120 my $e = find_encoding($c) or die "Unknown encoding: $c"; 121 $try{ $e->name } = $e; 122 DEBUG and warn "Added: ", $e->name; 123 } 124 my $nline = 1; 125 for my $line ( split /\r\n?|\n/, $octet ) { 126 127 # cheat 2 -- \e in the string 128 if ( $line =~ /\e/o ) { 129 my @keys = keys %try; 130 delete @try{qw/utf8 ascii/}; 131 for my $k (@keys) { 132 ref( $try{$k} ) eq 'Encode::XS' and delete $try{$k}; 133 } 134 } 135 my %ok = %try; 136 137 # warn join(",", keys %try); 138 for my $k ( keys %try ) { 139 my $scratch = $line; 140 $try{$k}->decode( $scratch, FB_QUIET ); 141 if ( $scratch eq '' ) { 142 DEBUG and warn sprintf( "%4d:%-24s ok\n", $nline, $k ); 143 } 144 else { 145 use bytes (); 146 DEBUG 147 and warn sprintf( "%4d:%-24s not ok; %d bytes left\n", 148 $nline, $k, bytes::length($scratch) ); 149 delete $ok{$k}; 150 } 151 } 152 %ok or return "No appropriate encodings found!"; 153 if ( scalar( keys(%ok) ) == 1 ) { 154 my ($retval) = values(%ok); 155 return $retval; 156 } 157 %try = %ok; 158 $nline++; 159 } 160 $try{ascii} 161 or return "Encodings too ambiguous: " . join( " or ", keys %try ); 162 return $try{ascii}; 163} 164 1651; 166__END__ 167 168=head1 NAME 169 170Encode::Guess -- Guesses encoding from data 171 172=head1 SYNOPSIS 173 174 # if you are sure $data won't contain anything bogus 175 176 use Encode; 177 use Encode::Guess qw/euc-jp shiftjis 7bit-jis/; 178 my $utf8 = decode("Guess", $data); 179 my $data = encode("Guess", $utf8); # this doesn't work! 180 181 # more elaborate way 182 use Encode::Guess; 183 my $enc = guess_encoding($data, qw/euc-jp shiftjis 7bit-jis/); 184 ref($enc) or die "Can't guess: $enc"; # trap error this way 185 $utf8 = $enc->decode($data); 186 # or 187 $utf8 = decode($enc->name, $data) 188 189=head1 ABSTRACT 190 191Encode::Guess enables you to guess in what encoding a given data is 192encoded, or at least tries to. 193 194=head1 DESCRIPTION 195 196By default, it checks only ascii, utf8 and UTF-16/32 with BOM. 197 198 use Encode::Guess; # ascii/utf8/BOMed UTF 199 200To use it more practically, you have to give the names of encodings to 201check (I<suspects> as follows). The name of suspects can either be 202canonical names or aliases. 203 204CAVEAT: Unlike UTF-(16|32), BOM in utf8 is NOT AUTOMATICALLY STRIPPED. 205 206 # tries all major Japanese Encodings as well 207 use Encode::Guess qw/euc-jp shiftjis 7bit-jis/; 208 209If the C<$Encode::Guess::NoUTFAutoGuess> variable is set to a true 210value, no heuristics will be applied to UTF8/16/32, and the result 211will be limited to the suspects and C<ascii>. 212 213=over 4 214 215=item Encode::Guess->set_suspects 216 217You can also change the internal suspects list via C<set_suspects> 218method. 219 220 use Encode::Guess; 221 Encode::Guess->set_suspects(qw/euc-jp shiftjis 7bit-jis/); 222 223=item Encode::Guess->add_suspects 224 225Or you can use C<add_suspects> method. The difference is that 226C<set_suspects> flushes the current suspects list while 227C<add_suspects> adds. 228 229 use Encode::Guess; 230 Encode::Guess->add_suspects(qw/euc-jp shiftjis 7bit-jis/); 231 # now the suspects are euc-jp,shiftjis,7bit-jis, AND 232 # euc-kr,euc-cn, and big5-eten 233 Encode::Guess->add_suspects(qw/euc-kr euc-cn big5-eten/); 234 235=item Encode::decode("Guess" ...) 236 237When you are content with suspects list, you can now 238 239 my $utf8 = Encode::decode("Guess", $data); 240 241=item Encode::Guess->guess($data) 242 243But it will croak if: 244 245=over 246 247=item * 248 249Two or more suspects remain 250 251=item * 252 253No suspects left 254 255=back 256 257So you should instead try this; 258 259 my $decoder = Encode::Guess->guess($data); 260 261On success, $decoder is an object that is documented in 262L<Encode::Encoding>. So you can now do this; 263 264 my $utf8 = $decoder->decode($data); 265 266On failure, $decoder now contains an error message so the whole thing 267would be as follows; 268 269 my $decoder = Encode::Guess->guess($data); 270 die $decoder unless ref($decoder); 271 my $utf8 = $decoder->decode($data); 272 273=item guess_encoding($data, [, I<list of suspects>]) 274 275You can also try C<guess_encoding> function which is exported by 276default. It takes $data to check and it also takes the list of 277suspects by option. The optional suspect list is I<not reflected> to 278the internal suspects list. 279 280 my $decoder = guess_encoding($data, qw/euc-jp euc-kr euc-cn/); 281 die $decoder unless ref($decoder); 282 my $utf8 = $decoder->decode($data); 283 # check only ascii, utf8 and UTF-(16|32) with BOM 284 my $decoder = guess_encoding($data); 285 286=back 287 288=head1 CAVEATS 289 290=over 4 291 292=item * 293 294Because of the algorithm used, ISO-8859 series and other single-byte 295encodings do not work well unless either one of ISO-8859 is the only 296one suspect (besides ascii and utf8). 297 298 use Encode::Guess; 299 # perhaps ok 300 my $decoder = guess_encoding($data, 'latin1'); 301 # definitely NOT ok 302 my $decoder = guess_encoding($data, qw/latin1 greek/); 303 304The reason is that Encode::Guess guesses encoding by trial and error. 305It first splits $data into lines and tries to decode the line for each 306suspect. It keeps it going until all but one encoding is eliminated 307out of suspects list. ISO-8859 series is just too successful for most 308cases (because it fills almost all code points in \x00-\xff). 309 310=item * 311 312Do not mix national standard encodings and the corresponding vendor 313encodings. 314 315 # a very bad idea 316 my $decoder 317 = guess_encoding($data, qw/shiftjis MacJapanese cp932/); 318 319The reason is that vendor encoding is usually a superset of national 320standard so it becomes too ambiguous for most cases. 321 322=item * 323 324On the other hand, mixing various national standard encodings 325automagically works unless $data is too short to allow for guessing. 326 327 # This is ok if $data is long enough 328 my $decoder = 329 guess_encoding($data, qw/euc-cn 330 euc-jp shiftjis 7bit-jis 331 euc-kr 332 big5-eten/); 333 334=item * 335 336DO NOT PUT TOO MANY SUSPECTS! Don't you try something like this! 337 338 my $decoder = guess_encoding($data, 339 Encode->encodings(":all")); 340 341=back 342 343It is, after all, just a guess. You should alway be explicit when it 344comes to encodings. But there are some, especially Japanese, 345environment that guess-coding is a must. Use this module with care. 346 347=head1 TO DO 348 349Encode::Guess does not work on EBCDIC platforms. 350 351=head1 SEE ALSO 352 353L<Encode>, L<Encode::Encoding> 354 355=cut 356 357