我正在开发一个带有大字典的
Android文字游戏 –
单词(超过700 000)在文本文件中保存为单独的行(然后放入sqlite数据库中).
为了防止竞争对手提取我的字典,我想用md5编码长度超过3个字符的所有单词. (我不会用简短的俄语字母ъ和э混淆简短的单词和单词,因为我想在我的应用程序中列出它们).
所以这是我尝试在Mac Yosemite上使用perl v5.18.2运行的脚本:
- #!/usr/bin/perl -w
- use strict;
- use utf8;
- use Digest::MD5 qw(md5_hex);
- binmode(STDIN,":utf8");
- #binmode(STDOUT,":raw");
- binmode(STDOUT,":utf8");
- while(<>) {
- chomp;
- next if length($_) < 2; # ignore 1 letter junk
- next if /жы/; # impossible combination in Russian
- next if /шы/; # impossible combination in Russian
- s/ё/е/g;
- #print "ORIGINAL WORD $_\tENCODED WORD: ";
- if (length($_) <= 3 || /ъ/ || /э/) { # do not obfuscate short words
- print "$_\n"; # and words with rare letters
- next;
- }
- print md5_hex($_) . "\n"; # this line crashes
- }
正如你所看到的,我必须在我的Perl脚本的源代码中使用西里尔字母 – 这就是我使用utf8的原因;在它的顶部.
但是我真正的问题是长度($_)报告的值太高(可能是报告字节数而不是字符数).
所以我尝试添加:
- binmode(STDOUT,":raw");
要么:
- binmode(STDOUT,":utf8");
但是脚本然后在带有print md5_hex($_)的行的子例程条目中以宽字符终止.
请帮我修改我的脚本.
我把它当作:
- perl ./generate-md5.pl < words.txt > encoded.txt
这里是示例words.txt数据为方便起见:
- а
- аб
- абв
- абвг
- абвгд
- съемка
解决方法
md5_hex需要输入一个字节字符串,但是您要传递一个已解码的字符串(一串Unicode代码点).显式编码字符串.
- use strict;
- use utf8;
- use Digest::MD5;
- use Encode;
- # ....
- # $_ is assumed to be utf8 encoded without check
- print Digest::MD5::md5_hex(Encode::encode_utf8($_)),"\n";
- # Conversion only when required:
- print Digest::MD5::md5_hex(utf8::is_utf8($_) ? Encode::encode_utf8($_) : $_),"\n";