【发布时间】:2019-04-17 15:52:15
【问题描述】:
在 Windows 10 上使用 Strawberry perl v5.28.1,我试图获得与在 Linux 上相同的结果 - 即获得一个 带有 Unix 行结尾的 UTF8 编码文件。
这是我的 Perl 脚本:
#!perl -w
use strict;
use utf8;
use Encode qw(encode_utf8);
use Digest::MD5 qw(md5_hex);
binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");
my %words;
while(<>) {
# change yo to ye
tr/ёЁ/еЕ/;
# extract russian word and its optional explanation
next unless /^([А-Я]{2,})\|?([А-Я ,-]*)/i;
my ($word, $expl) = (uc $1, $2);
if (length($word) <= 3) {
print $word;
# if explanation is missing, omit the pipe
print (length($expl) > 3 ? "|$expl\x0A" : "\x0A");
} else {
# print the md5 hash and omit the pipe and explanation
print md5_hex(encode_utf8('my secret' . $word)) . "\x0A";
}
}
这是我的输入文件:
ААК|Плоскодонное речное судно
ААРОНОВЕЦ|
ААРОНОВЩИНА|
ААТ|Драгоценный красный камень в Японии
АБА|Толстое и редкое белое сукно
АБАЖУР|
АБАЖУРОДЕРЖАТЕЛЬ|
АБАЗ|Грузинская серебряная монета
АБАЗА|
这是我的运行方式(我使用type 而不是<,因为在我的实际用例中有大量输入文件):
type input.txt | perl encode-words-ru.pl > output.txt
无论我在上面的 Perl 源代码中尝试什么,output.txt 中的行都以 \x0D\x0A 终止
请帮助我阻止 perl “帮助”我!
【问题讨论】:
-
来自perlio documentation: 如果您希望在通常进行 CRLF 转换的平台上使用 UNIX 行结尾,但仍需要 UTF-8 或编码默认值,则适当的做法是添加: perlio 到 PERLIO 环境变量。 可能值得研究这种方法。
-
你也应该使用
:encoding(UTF-8),而不是:utf8,顺便说一句 -
很遗憾,您的两个建议都没有帮助:
@SET PERLIO='perlio'和binmode(STDOUT, ":encoding(UTF-8)"); -
它说使用
:perlio而不是perlio。冒号很重要。 (我目前无法使用 Windows 计算机进行自己的测试)。 -
我链接的文档解释了为什么
:encoding(UTF-8)更可取(尽管大多数示例都没有使用它,叹息)。