http://www.perlmonks.org?node_id=814129

jbert has asked for the wisdom of the Perl Monks concerning the following question:

Hi folks,

It seems to me that mod_perl2 isn't doing the right thing wrt utf8.

This seems unlikely to me (it's widely used software), so I'd appreciate a second opinion.

Here are two ways of constructing a string containing the unicode character U+00B4 (ACUTE ACCENT):

binmode STDOUT, ':utf8'; my $strA = "Bob\x{B4}s files"; use Encode; my $strB = Encode::decode_utf8("Bob\xC2\xB4s files"); say "strA is $strA"; say "strA is $strB"; say "strings are " . (($strA eq $strB) ? "eq" : "not eq"); say "strA flag is: ".Encode::is_utf8($strA); say "strB flag is: ".Encode::is_utf8($strB);

Because the U+00B4 is within latin1 perl is willing and able to treat strA as a byte-string (no utf8 flag set) as per perldoc perlunicode docco for \x: for characters under 0x100, note that Perl may use an 8 bit encoding internally, for optimization and/or backward compatibility.

If I have a mod_perl2 handler which just sends text/plain utf8 content and send those two strings via $r->print then I see different results in the browser (strA doesn't render correctly). Note that $r->binmode seems to do nothing.

To me, this is a mod_perl bug. In perl, the strings are equivalent. It seems mod_perl2 is ignoring the is_utf8 flag and only sending the raw internal representation (latin1 for strA and utf8 for strB).

That said, this has surely been gone over before, so could someone please put me straight.

(Workaround 1 - avoid use of \x escapes and either use decode_utf8 to build string literals or the use utf8; pragma and literal utf8 sequences in your source.)

(Workaround 2 - if your strings come from an external source (e.g. Data::Dumper) you can do:

if (!Encode::is_utf8($str) && $str =~ m/\x80-\xff/) { $str = Encode::encode_utf8($str); # Get utf8 byte seq Encode::_utf8_on($str); # and flip the flag }

But that's fugly since it assumes loads about internals and has a runtime cost which isn't always fun.