2011-01-20 64 views
0

我發現這個示例腳本從How can I guess the encoding of a string in Perl?如何在Perl中將字符編碼爲數字字符參考格式?

#!C:\perl\bin 
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', $string, XMLCREF); # This year I went to 北京 Perl workshop. 

具有測試後,我發現了編碼輸出結果爲:

This year I went to \x{71fa9} Perl workshop. 
This year I went to 񱾩 Perl workshop. 

貌似結果不同於一個作者顯示了我們上述示例代碼。

我不知道我怎麼能編碼字符串,並使其在numeric character reference格式(&#xHHHH;)輸出時,例如:

my $string = 'This year I went to 北京 Perl workshop.'; 

編碼的輸出將是:

This year I went to 北京 Perl workshop. 
+0

我的測試輸出看起來像這樣今年我去了񱾩 Perl研討會。 – user583552 2011-01-20 20:46:26

回答

0
$string =~ s/[^\0-\377]/ sprintf '&#x%04x;', ord($&) /ge 

找到$string中的每個字符都不在0-255範圍內(即任何寬字符),並將其替換爲表達式的值,其中$&是匹配的寬字符。

use utf8; 
$string = "This year I went to \x{5317}\x{4eac} Perl workshop."; 
$string =~ s/[^\0-\377]/ sprintf '&#x%04x;', ord($&) /ge; 
print $string; 

產地:

 
This year I went to 北京 Perl workshop. 
1

我在這個問題掛鉤答案的作者。


您犯了一個簡單的錯誤,您保存了GB18030中的Perl程序。當它包含use utf8;時,您必須改爲save it in UTF-8

相關問題