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


in reply to Re^4: Why does Encode::Repair only correctly fix one of these two tandem characters?
in thread Why does Encode::Repair only correctly fix one of these two tandem characters?

The following tool takes out having to do all the hard, error-prone work.
use strict; use warnings; use Encode qw( encode decode ); { my @charset = grep $_ ne "\x{FFFD}", map decode('cp1252', chr($_)), 0x00..0xFF; my %map; for my $dec (@charset) { my $enc = encode 'UTF-8', decode 'cp1252', encode 'UTF-8', $dec; push @{ $map{$enc} }, $dec; } for (values(%map)) { warn(sprintf("Ambiguous: %v04X\n", join '', @$_)) if @$_ > 1; $_ = $_->[0]; } my $pat = join '|', map quotemeta, sort { length($b) <=> length($a) || $a cmp $b } keys %map; my $re = qr/$pat/; while (<>) { s/\G(?:($re)|(.))/ if ($1) { $map{$1} } else { die("Unrecognized sequence starting at pos", $-[2]); } /seg; } }

It also finds that you have a problem. You can't tell the difference between the following cp1252 characters after they've gone through your encoding-decoding gauntlet:

Verification:

$ perl -MEncode -E' say sprintf "%v02X", encode "UTF-8", decode "cp1252", encode "UTF-8", chr for 0x00C1, 0x00CD, 0x00CF, 0x00D0, 0x00DD; ' C3.83.EF.BF.BD C3.83.EF.BF.BD C3.83.EF.BF.BD C3.83.EF.BF.BD C3.83.EF.BF.BD

Note: I didn't have the tool check if one messed up sequence can be a substring of another messed up sequence. The sorting by descending length is there to try to handle that case if it exists. Upd: No such case exists.