http://www.perlmonks.org?node_id=542225

jbrugger has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,
I want to check the encoding of a file, since i need to convert all my templates to utf8, but not the ones that are utf8, since they will be double encoded (using iconf)
However, after supersearching i came up with the following possible solution:
#!/usr/bin/perl -w use strict; use File::BOM qw( :all ); open_bom(FH, "test.txt", 'bytes'); my $encoding = get_encoding_from_filehandle(FH); print $encoding . "\n\n";
This is not returning anything however.
for now, we started to use (opening each file and parsing it in the encoder):
use Encode::Guess; my $decoder = guess_encoding($arg->{String}, 'latin1'); if (ref($decoder)) { return 0; } else { return 1; }
For the rest i did not find any other way of dertermining the encoding of a file, anyone knows what is wrong with File::BOM or does anyone have a better solution?
Thanks!
"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.

Replies are listed 'Best First'.
Re: how to check the encoding of a file
by ysth (Canon) on Apr 10, 2006 at 11:16 UTC
    This came up before in What encoding am I (probably) using?, but it sounds like in your case you are just choosing between latin1 and utf8? If so, the best way may be to just check if it is valid utf8, and only if it isn't assume it is latin1. You can simply use utf8::decode to do this.
Re: how to check the encoding of a file
by graff (Chancellor) on Apr 11, 2006 at 02:34 UTC
    I haven't used File::BOM, but I gather it will only work if the input data actually contains a byte-order-mark character (in fact, if it begins with said character); assuming this isn't true of your data, it won't help you much.

    To elaborate on the first reply (which is basically correct, if you are in fact only deciding between Latin-1 and utf8), check the section about "Handling Malformed Data" in the Encode man page: basically, use the "decode" function like this:

    #!/usr/bin/perl use strict; use Encode; die "Usage: $0 latin1.file > utf8.file" unless ( @ARGV == 1 and -f $ARGV[0] ); open( my $fh, "<", $ARGV[0] ) or die "$ARGV[0]: $!"; { local $/; $_ = <$fh>; close $fh; } my $utf8; eval { $utf8 = decode( "utf8", $_, Encode::FB_CROAK ) }; if ( $@ ) { # input was not utf8 $utf8 = decode( "iso-8859-1", $_, Encode::FB_WARN ); } binmode STDOUT, ":utf8"; print $utf8;

    If you have to decide between utf8, Latin1, Latin2, Cyrillic, Greek, etc, then you have a harder job: to the extent that the non-Latin1 encodings use the same 8-bit range as Latin-1, Encode will happily pretend that they are all Latin-1, thereby converting them all to the wrong set of utf8 characters.

    Encode::guess probably won't help you in that case -- you need to train up some bigram character models for each language... (well, maybe the Lingua branch on CPAN has something to handle this by now).