use strict; use Encode; # my raw data my $data = "\xe0\xe1\x02\n"; # interpret it as text in encoding CP1251 my $txt = Encode::decode("cp1251", $data); # convert text to octets in encoding Latin1. # Replace bad ones with X my $nd = Encode::encode("latin1", $txt, sub{ return "X" }); # just to see the result in the terminal which uses UTF-8 encoding Encode::from_to($nd, "latin1", "UTF-8"); print $nd, "\n"