in reply to Converting UTF8 to ANSI
\x{EF}\x{BB}\x{BF} is the UTF-8 BOM, but because you're looking for the UTF-8 encoded BOM EF BB BF instead of the Unicode character U+FEFF, that tells me you haven't opened the file with the right encoding, and personally I think decoding afterwards is more of a pain than opening the file with the right encoding in the first place. Also, by "ANSI" I assume you mean Windows-1252. Anyway, if you are certain that all of your UTF-8 encoded files begin with a BOM, you can use File::BOM, the following will open files that have a BOM with the proper encoding, but fall back to CP-1252 if they don't:
use File::BOM qw/open_bom/; open_bom(my $fh, $filename, ':encoding(cp1252)');
Otherwise, if you have no sure way of telling the files apart, you may have to use Encode::Guess, with the caveat that it's just a guess. Something like this maybe:
use Encode::Guess; open my $fh, '<:raw', $filename or die $!; read $fh, my $buf, 1024; # may need bigger buffer for better guess? close $fh; my $enc = guess_encoding($buf, qw/cp1252 utf8 UTF-16/); ref($enc) or die "Can't guess $filename: $enc"; print "$filename: guessed ",$enc->name,"\n"; #Debug open $fh, '<:encoding('.$enc->name.')', $filename or die $!;
In both cases, you may want to strip the BOM off the beginning of the data read from the file via $data =~ s/\A\x{FEFF}//;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Converting UTF8 to ANSI
by ikegami (Patriarch) on Aug 28, 2017 at 04:26 UTC | |
by Your Mother (Archbishop) on Aug 29, 2017 at 18:11 UTC | |
by palkia (Monk) on Aug 29, 2017 at 18:05 UTC | |
|
Re^2: Converting UTF8 to ANSI
by palkia (Monk) on Aug 29, 2017 at 18:02 UTC | |
by haukex (Archbishop) on Aug 29, 2017 at 19:45 UTC | |
by AnomalousMonk (Archbishop) on Aug 29, 2017 at 19:10 UTC |