windows - 如何在Windows 10中的perl> = 5.18中强制为输出文件设置代码集cp1252?

标签 windows perl encoding strawberry-perl cp1252

我需要确保用我的perl脚本创建的输出文件具有代码集cp1252,而不是UTF-8,因为它将在UNIX SQLplus框架内使用,该框架在将值插入数据库时​​无法正确处理德语“变音符”列(我在Windows 10中使用Strawberry Perl v5.18,并且无法在UNIX SQL环境中设置NLS_LANG或chcp)。

使用这个小的测试脚本,我可以重现输出文件“testfile1.txt”始终以UTF-8格式显示,而“testfile2.txt”为CP1252正是所期望的。
即使文本中没有“特殊”字符,我如何强制“testfile1.txt”的输出也为CP1252?

#!/usr/bin/env perl -w
use strict;
use Encode;

# the result file under Windows 10 will have UTF-8 codeset
open(OUT,'> testfile1.txt');    
binmode(OUT,"encoding(cp-1252)");
print OUT encode('cp-1252',"this is a test");
close(OUT);

# the result file under Windows 10 will have Windows-cp1252 codeset
open(OUT,'> testfile2.txt');    
binmode(OUT,"encoding(cp-1252)");
print OUT encode('cp-1252',"this is a test with german umlauts <ÄäÜüÖöß>");
close(OUT);

最佳答案

我认为您的问题是基于误解。 testfile1.txt包含文本this is a test。这些字符在ASCII,Latin-1,UTF-8和CP-1252中具有相同的编码。 testfile1.txt同时在所有这些编码中均有效。

要在源代码中包含文字Unicode字符,如下所示:

print OUT encode('cp-1252',"this is a test with german umlauts <ÄäÜüÖöß>");

你需要
use utf8;

在顶部。

另外,请勿将文件句柄上的编码层与显式的encode()调用结合使用。要么设置编码层并在其中打印Unicode文本,要么使用binmode(OUT)并在其上打印原始字节(从encode()返回)。

顺便说一句,您不应该再使用-w了。它已经被
use warnings;

实用

同样,裸字文件句柄和带有两个参数的open是5.6之前的样式代码,不应在2000年之后编写的代码中使用。(perl 5.005和更早版本始终不支持Unicode/编码。)

固定版本的代码如下所示:
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;

{
    open(my $out, '>:encoding(cp-1252)', 'testfile1.txt') or die "$0: testfile1.txt: $!\n";    
    print $out "this is a test\n";
    close($out);
}

{
    open(my $out, '>encoding(cp-1252)', 'testfile2.txt') or die "$0: testfile2.txt: $!\n";    
    print $out "this is a test with german umlauts <ÄäÜüÖöß>\n";
    close($out);
}

关于windows - 如何在Windows 10中的perl> = 5.18中强制为输出文件设置代码集cp1252?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47057930/

相关文章:

windows - 为什么 Strawberry Perl 不调用我的 DllMain?

python - pool.map 列表索引超出范围 python

windows - 使用 NAudio 获取输入设备支持的格式

perl - 如何使用 WWW::Mechanize 或任何 Perl 模块下载文件?

perl - 强制 Ale 将 Perl::Critic 违规显示为警告而不是错误

windows - 在 NSIS 中导入注册表项时出错

mysql - 使用 Perl 在 MySQL 中插入日期

python 2.7 : How can I pass in arguments such as 'café' from the shell and not get 'cafÚ' ?

python - urllib : get utf-8 encoded site source code

python - 这个编码是什么以及如何转换它?