【问题标题】:How do I save a file as UTF-8 from Perl?如何从 Perl 将文件保存为 UTF-8?
【发布时间】:2011-01-21 08:05:33
【问题描述】:

我正在尝试以 UTF-8 格式在 Perl 中创建/保存 HTML 文件,但到目前为止我没有做任何事情。 previous answer here on SO 说要使用 binmode,所以我试了一下。这是我的代码:

open (OUT, ">$sectionfilename");
binmode(OUT, ":utf8");
print OUT $section;
close OUT;

当我在记事本等文本编辑器中打开这些文件时,它们仍然采用 ANSI 编码。我做错了什么?

【问题讨论】:

  • 您想要 BOM(字节顺序标记)?
  • 您是指专门的记事本吗?因为记事本无法识别没有 BOM 的 UTF-8。
  • 不,不只是记事本,TextPad 也一样。该文件只是没有编码为 UTF-8。

标签: perl utf-8


【解决方案1】:

文本编辑器是检查编码等低级事物的糟糕工具。请改用 hexviewer/hexdumper。编写示例的现代方式:

use autodie qw(:all);
open my $out, '>:encoding(UTF-8)', $sectionfilename;
print {$out} $section;
close $out;

autodie 启用自动错误检查。

【讨论】:

    【解决方案2】:

    似乎对我有用:

    C:\Documents and Settings>cat a.pl
    $sectionfilename = "a.txt";
    $section = "Hello \x{263A}!\n";
    
    open (OUT, ">$sectionfilename");
    binmode(OUT, ":utf8");
    print OUT $section;
    close OUT;    
    
    C:\Documents and Settings>perl a.pl
    
    C:\Documents and Settings>file a.txt
    a.txt: UTF-8 Unicode text, with CRLF line terminators
    

    但是当我更改要写入的文本时:

    $section = "Hello";
    

    然后运行:

    C:\Documents and Settings>perl a.pl
    
    C:\Documents and Settings>file a.txt
    a.txt: ASCII text, with no line terminators
    

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多