【问题标题】:How can I output a UTF-8 encoded XML file with unix line-endings from ActivePerl on Windows?如何在 Windows 上从 ActivePerl 输出带有 unix 行尾的 UTF-8 编码 XML 文件?
【发布时间】:2011-02-14 05:13:19
【问题描述】:

我在 WinXP 上运行 ActivePerl 5.8.8。我想将 XML 文件输出为 UTF-8 并以 UNIX 行结尾。

我查看了 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);
}

【问题讨论】:

  • 我很好奇你为什么关心行尾。 XML 不在乎。无论你用什么读回文件都不应该在意。
  • 您打算使用my $File = "SAVE"; 实现什么目标?
  • @AmbroseChapel:我同意,我们不应该关心,但是(图书馆管理系统 - Ex Libris' Aleph)软件很挑剔。

标签: perl unix file winapi utf-8


【解决方案1】:

如果 $Contents 还没有 \n 字符,print 将不会为您添加它们。你必须自己做。

还有其他一些可能有问题的事情;以下是修复它们的方法和原因。

IO Layers

要启用 utf8 输出,您需要使用 :utf8,而不是 :utf-8。另外,你的 IO 层中不应该有空格,所以它应该看起来像 `">:utf8:unix"。

Open

open一个文件,可以在行中声明'my $fh';无需将其初始化为字符串即可开始。没关系,这是个好习惯。此外,使用or 是捕获打开错误的首选方法。

改变了,你的代码现在看起来像这样:

sub SaveFile
{
    my($FileName, $Contents) = @_;

    open my $File, ">:utf8:unix", $FileName
        or die "Cannot open $FileName";
    print $File map { "$_\n" } @$Contents;

    close($File);
}

map 允许您通过在每行打印之前添加换行符来转换输入数组,并按顺序执行。

祝你好运!

【讨论】:

    【解决方案2】:

    我认为你需要这样的东西。

    use strict;
    use warnings;
    
    sub save_file {
        my ($file_name, $content) = @_;
        open my $fh, ">", $file_name or die $!;
        binmode $fh, ':utf8 :unix';
        print $fh @$content;
        close $fh;
    }
    
    # For example.
    save_file('foo.txt', [ map "$_\n", qw(foo bar baz)]);
    

    对于open 的3 参数形式的典型用法,您希望在调用open 之前未定义文件句柄变量。详情请见the docs

    【讨论】:

    • 这在我的 XP 环境中输出 UTF-8 而不是 UNIX 行结尾。
    • @Umber Ferrule 不确定是什么问题。它适用于我的 XP,包括 Unix 换行符。这是文件的转储:666f 6f0a 6261 720a 6261 7a0a.
    猜你喜欢
    • 2018-09-20
    • 2012-09-04
    • 2011-03-16
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 2014-04-26
    • 2022-07-20
    • 1970-01-01
    相关资源
    最近更新 更多