我在 WinXP 上运行 ActivePerl 5.8.8。我想将 XML 文件输出为带有 UNIX 行结尾的 UTF-8。
我查看了 binmode
的 perldoc ,但不确定确切的语法(如果我没有找错树的话)。以下不这样做(原谅我的 Perl - 这是一个学习过程!):
sub SaveFile
{
my($FileName, $Contents) = @_;
my $File = "SAVE";
unless( open($File, ">:utf-8 :unix", $FileName) )
{
die("Cannot open $FileName");
}
print $File @$Contents;
close($File);
}
最佳答案
如果 $Contents 还没有 \n
字符,print
将不会为您添加它们。你必须自己做。
还有其他一些问题可能存在;以下是修复它们的方法和原因。
要启用utf8 输出,您需要使用:utf8
,而不是:utf-8
。此外,你的 IO 层不应该有空格,所以它应该看起来像 `">:utf8:unix"。
要打开
一个文件,你可以在行中声明'my $fh';无需将其初始化为字符串即可启动。没关系,这是很好的做法。此外,使用 或
是捕获打开错误的首选方法。
改变了一下,你的代码现在看起来像这样:
sub SaveFile
{
my($FileName, $Contents) = @_;
open my $File, ">:utf8:unix", $FileName
or die "Cannot open $FileName";
print $File map { "$_\n" } @$Contents;
close($File);
}
map允许您通过在打印前向每一行添加换行符来转换输入数组,并按顺序进行。
祝你好运!
关于perl - 如何从 Windows 上的 ActivePerl 输出带有 unix 行结尾的 UTF-8 编码 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2744312/