我有一个Unicode字符串,不知道它的编码是什么。当这个字符串被Perl程序读取时,Perl会使用默认的编码吗?如果是这样,我怎么知道它是什么?
我正在尝试从输入中删除非ASCII字符。我在一些论坛上发现了这一点
my $line = encode('ascii',normalize('KD',$myutf),sub {$_[0] = ''});
当没有指定输入编码时,上述工作如何工作?应该如此指定吗?
my $line = encode('ascii',decode($myutf,'input-encoding'),sub {$_[0] = ''});
解决方法
要了解未知使用的编码,您只需要尝试看看。模块
Encode::Detect和
Encode::Guess自动化。 (如果编译Encode :: Detect时遇到问题,请尝试使用其fork
Encode::Detective))
use Encode::Detect::Detector; my $unknown = "\x{54}\x{68}\x{69}\x{73}\x{20}\x{79}\x{65}\x{61}\x{72}\x{20}". "\x{49}\x{20}\x{77}\x{65}\x{6e}\x{74}\x{20}\x{74}\x{6f}\x{20}". "\x{b1}\x{b1}\x{be}\x{a9}\x{20}\x{50}\x{65}\x{72}\x{6c}\x{20}". "\x{77}\x{6f}\x{72}\x{6b}\x{73}\x{68}\x{6f}\x{70}\x{2e}"; my $encoding_name = Encode::Detect::Detector::detect($unknown); print $encoding_name; # gb18030 use Encode; my $string = decode($encoding_name,$unknown);
我发现编码’ascii’是摆脱非ASCII字符的跛脚解决方案。一切将被问号所取代;这太有用了。
# Bad example; don't do this. use utf8; use Encode; my $string = 'This year I went to 北京 Perl workshop.'; print encode('ascii',$string); # This year I went to ?? Perl workshop.
如果你想要可读的ASCII文本,我建议使用Text::Unidecode。这也是有损编码,但不像上面的纯编码那么可怕。
use utf8; use Text::Unidecode; my $string = 'This year I went to 北京 Perl workshop.'; print unidecode($string); # This year I went to Bei Jing Perl workshop.
但是,如果可以帮助它,请避免这些有损编码。如果以后要反转操作,请选择PERLQQ或XMLCREF中的任何一个。
use utf8; use Encode qw(encode PERLQQ XMLCREF); my $string = 'This year I went to 北京 Perl workshop.'; print encode('ascii',$string,PERLQQ); # This year I went to \x{5317}\x{4eac} Perl workshop. print encode('ascii',XMLCREF); # This year I went to 北京 Perl workshop.