回答您上一条评论中的问题,以下是如何从一种编码转换为另一种编码:
#!/usr/bin/perl
use strict;
use warnings;
sub read_encoded {
my $file_name = shift;
my $encoding = shift;
my $content;
if ( open my $fh, "<:encoding($encoding)", $file_name ) {
$content = do {
local $/;
<$fh>;
};
}
else {
die "Could not open $file_name: $!";
}
return $content;
}
sub write_file {
my $file_name = shift;
my $content = shift;
if ( open my $fh, '>:encoding(UTF-8)', $file_name ) {
print $fh $content;
}
else {
die "Could not open $file_name: $!";
}
}
my $content1 = read_encoded( 'file1.txt', 'latin-1' );
my $content2 = read_encoded( 'file2.txt', 'UTF-16BE' );
write_file( 'output', $content1 . $content2 );
假设您有两个文件file1.txt
和file2.txt
,分别以 latin-1 和 UTF-16BE 编码,这个小脚本将读取这两个文件并将输出写入名为 的 UTF-8 编码文件output
。