当Perl打开一个UTF-16编码文件时,
open my $in, "< :encoding(UTF-16)", "text-utf16le.txt" or die "Error $!\n";
它自动检测恩典谢字节顺序标记。
但是当我打开文件写
open my $out, "> :encoding(UTF-16)", "output.txt" or die "Error $!\n";
默认情况下,Perl以大endian的形式打开它。
请指定以与输入文件相同的权限打开输出文件?
如何从输入文件句柄$in获得endianness/编码?PerlIO::get_layers($in)返回其他层encoding(UTF-16)。
发布于 2015-03-04 15:14:01
你得自己读BOM。
use IO::Unread qw( unread );
open(my $fh_in, "<:raw", $qfn)
or die;
my $rv = read($fh_in, my $buf, 4);
defined($rv)
or die;
my $encoding;
my $bom_present;
if ($buf =~ s/^\x00\x00\xFE\xFF//) { $encoding = 'UTF-32be'; $bom_present = 1; }
elsif ($buf =~ s/^\xFF\xFE\x00\x00//) { $encoding = 'UTF-32le'; $bom_present = 1; }
elsif ($buf =~ s/^\xFE\xFF// ) { $encoding = 'UTF-16be'; $bom_present = 1; }
elsif ($buf =~ s/^\xFF\xFE// ) { $encoding = 'UTF-16le'; $bom_present = 1; }
elsif ($buf =~ s/^\xEF\xBB\xBF// ) { $encoding = 'UTF-8'; $bom_present = 1; }
else {
$encoding = 'UTF-8';
$bom_present = 0;
}
unread($fh_in, $buf) if length($buf);
binmode($fh_in, ":encoding($encoding)");
binmode($fh_in, ":crlf") if $^O eq 'MSWin32';但已经有人为你这么做了
use File::BOM qw( open_bom );
my $encoding = open_bom(my $fh_in, $qfn, ':encoding(UTF-8)');https://stackoverflow.com/questions/28857025
复制相似问题