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


in reply to Re^2: Detect the Charset of an file
in thread Detect the Charset of an file

You said:

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.

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"; }
Note that when given an ASCII file, the above will say "$filename IS UTF8", which of course is true.

UPDATE: Just noticed a missing semi-colon at the end of the eval block -- fixed it.