在人们开始将包含 utf8 字符的 Wikipedia 文本字符串复制并粘贴到输入字段之前,我有我认为将成为一个简单的 Web 表单的东西。我的 perl CGI 脚本打开一个 MySQL 数据库连接并设置
$DBH->{mysql_enable_utf8} = 1;
$DBH->do("set names 'utf8';");
我正在尝试使用 Encode
模块对目标输入值进行解码、使用和编码,但这并没有像我预期的那样工作。网页设置为utf8字符集。
在这种情况下,我的目标字符串是 Baden-Württemberg
[从列出德国城镇名称的维基百科页面复制]。发送请求后,我可以看到目标字符串为:Baden-W%C3%BCrttemberg
。不过,这并没有很好地通过我的 CGI 脚本。
我有以下示例脚本:
#!/usr/local/bin/perl -w
use strict;
select(STDOUT);
$|++;
use feature 'unicode_strings';
use Encode;
use utf8;
binmode STDOUT, ":utf8";
my $thing = "Baden-Württemberg";
print STDOUT "$thing\n";
my $decodedThing = decode_utf8($thing);
print STDOUT encode_utf8($decodedThing) . "\n";
$thing
的值在 '-W' 之后有一个带有变音符号的 'u'。
当我运行脚本时,我得到:
# ./test.pl
Malformed UTF-8 character (unexpected non-continuation byte 0x72, immediately after start byte 0xfc) at ./test.pl line 13.
Baden-Wrttemberg
Baden-Wrttemberg
u-umlaut 去哪儿了?我如何取回它?
最佳答案
问题1
您告诉 Perl 您的源文件是使用 UTF-8 编码的。
use utf8;
事实并非如此。 ü
在您的文件中由 FC
表示,而不是 C3 BC
。 (这就是您收到“格式错误”消息的原因。)修复源文件的编码。
mv file.pl file.pl~ && piconv -f iso-8859-1 -t UTF-8 file.pl~ >file.pl
问题2
以下是没有意义的:
my $decodedThing = decode_utf8($thing);
因为 use utf8;
,$thing
已经被解码了。
问题3
以下是没有意义的:
print STDOUT encode_utf8($decodedThing);
你要求 Perl 自动编码每一个发送到 STDOUT 的东西,所以你是双重编码。
固定
#!/usr/local/bin/perl
use strict;
use warnings;
use utf8;
use open ':std', ':encoding(UTF-8)';
my $thing = "Baden-Württemberg";
printf "U+%v04X\n", $thing; # U+[...].0057.00FC.0072.[...]
print "$thing\n"; # Baden-Württemberg
关于mysql - Perl 字符串操作和 utf8/unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29990827/