二进制模式(标准输出,“:utf8”);和 Strawberry perl 中的 Unix 行结尾

binmode(STDOUT, ":utf8"); and Unix line endings in Strawberry perl

在 Windows 10 上使用 Strawberry perl v5.28.1 我试图获得与在 Linux 上相同的结果 - 即获得一个 UTF8 编码文件 with Unix line endings.

这是我的 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 , );

        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

终止

请帮我阻止 "helping" 我的 perl!

可能有更好的方法,但您可以创建 STDOUT 一个 :raw 文件句柄,然后自己在那里对输出进行编码。

binmode STDOUT;    # or  binmode STDOUT, ":raw";
...
print (length($expl) > 3 ? encode_utf8("|$expl\n") : "\n");   # $exp1 is already decoded
...
print md5_hex(encode_utf8('my secret' . $word)) . "\n";