in reply to Re^2: Detect the Charset of an file
in thread Detect the Charset of an file
I only need some code to detect if the file is already utf8, then we don't do the recode.
The easiest way to check whether your data is utf8 is to read it as "raw" and try decoding it from utf8. If that succeeds, the data is clearly utf8. The reason why this is a good solution is that non-ASCII, non-utf8 data will virtually ALWAYS throw an error if you try to interpret it as utf8 data.
Note that when given an ASCII file, the above will say "$filename IS UTF8", which of course is true.use Encode; open( my $fh, "<:raw", $filename ) or die; local $/; $_ = <$fh>; eval { $_ = decode( 'utf8', $_, Encode::FB_CROAK ) }; if ( $@ ) { print "$filename is NOT UTF8\n"; } else { print "$filename IS UTF8\n"; }
UPDATE: Just noticed a missing semi-colon at the end of the eval block -- fixed it.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Detect the Charset of an file
by endymion (Acolyte) on Oct 23, 2013 at 06:48 UTC | |
by graff (Chancellor) on Oct 23, 2013 at 21:00 UTC | |
|
Re^4: Detect the Charset of an file
by Anonymous Monk on Oct 24, 2013 at 13:47 UTC |