Perl - 将PC UTF-8转换为PC ANSI

时间:2013-02-25 21:48:22

标签: perl unicode ansi

我有一个编码为PC UTF-8的文件。我想将文件转换为PC ANSI。

我已尝试过以下内容,但我总是将输出文件设为PC UTF-8。

use Encode;

$infile = $ARGV[0];
open(INFILE, $infile);

my $outfile = "temp.txt";

open(OUTFILE, ">$outfile");

while(<INFILE>) {
  my $row = $_;
  chomp $row;

  $row = Encode::encode("Windows-1252", $row);
  print OUTFILE $row."\n";

}

close INFILE;
close OUTFILE;

2 个答案:

答案 0 :(得分:9)

问题是你永远不会解码你编码的数据。

use strict;
use warnings;
use Encode qw( encode decode );

open(my $INFILE,  '<', $ARGV[0]) or die $!;
open(my $OUTFILE, '>', $ARGV[1]) or die $!;

while (my $utf8 = <$INFILE>) {
   my $code_points = decode('UTF-8', $utf8);    # <-- This was missing.
   my $cp1252 = encode('cp1252', $code_points);
   print $OUTFILE $cp1252;
}

但你可以更轻松地做到这一点:

use strict;
use warnings;

open(my $INFILE,  '<:encoding(UTF-8)',  $ARGV[0]) or die $!;
open(my $OUTFILE, '>:encoding(cp1252)', $ARGV[1]) or die $!;

while (<$INFILE>) {
   print $OUTFILE $_;
}

答案 1 :(得分:1)

您应该使用PerlIO-Layers,而不是手动解码和编码。您可以使用binmode函数指定图层,也可以在模式参数中指定为3-arg open

use strict; use warnings;
use autodie;

open my $INFILE,  '<:utf8',                 $ARGV[0];
open my $OUTFILE, '>:encoding(iso-8859-1)', "temp.txt";
#                   ^-- the layers

while (my $line = <$INFILE>) {
  print $OUTFILE $line;
}

请注意,Perl默认情况下不会将文件打开到UTF8,您还必须指定解码层。图层:encoding(utf8)非常常见,您可以直接说:utf8

您可以使用

列出所有可用的编码
use Encode;
print "$_\n" for Encode->encodings();