Alexander Farber Alexander Farber - 1 year ago 106
Perl Question

'Wide character in subroutine entry" - UTF-8 encoded cyrillic words as sequence of bytes

I am working on an Android word game with a large dictionary -

app screenshot

The words (over 700 000) are kept as separate lines in a text file (and then put in an SQLite database).

To keep competitors from extracting my dictionary, I'd like to encode all words which are longer than 3 chars with md5. (I don't obfuscate short words and words with rare Russian letters

, because I'd like to list them in my app).

So here is my script which I try to run with perl v5.18.2 on Mac Yosemite:

#!/usr/bin/perl -w

use strict;
use utf8;
use Digest::MD5 qw(md5_hex);

binmode(STDIN, ":utf8");
#binmode(STDOUT, ":raw");
binmode(STDOUT, ":utf8");

while(<>) {
next if length($_) < 2; # ignore 1 letter junk
next if /жы/; # impossible combination in Russian
next if /шы/; # impossible combination in Russian



if (length($_) <= 3 || /ъ/ || /э/) { # do not obfuscate short words
print "$_\n"; # and words with rare letters

print md5_hex($_) . "\n"; # this line crashes

As you can see, I have to use cyrillic letters in the source code of my Perl script - that is why I've put
use utf8;
on its top.

However my real problem is that
reports too high values (probably reporting number of bytes instead of number of characters).

So I have tried adding:

binmode(STDOUT, ":raw");


binmode(STDOUT, ":utf8");

But the script then dies with Wide character in subroutine entry at the line with
print md5_hex($_)

Please help me to fix my script.

I run it as:

perl ./ < words.txt > encoded.txt

and here is example words.txt data for your convenience:


Answer Source

md5_hex expects a string of bytes for input, but you're passing a decoded string (a string of Unicode Code Points). Explicitly encode the string.

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download