如何从Perl将文件保存为UTF-8?

时间:2010-02-26 05:53:33

标签: perl utf-8

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

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

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

2 个答案:

答案 0 :(得分:14)

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

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

autodie启用自动错误检查。

答案 1 :(得分:3)

似乎对我有用:

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