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


in reply to Database vs XML output representation of two-byte UTF-8 character

Can anyone explain why this is happening?
1) Internally, Perl has two different kinds of strings. We'll call them 'binary' and 'unicode' strings.
$ perl -MDevel::Peek -e 'Dump "Я"'
FLAGS = (POK,READONLY,IsCOW,pPOK)
This is a binary string.
$ perl -MDevel::Peek -e 'use utf8; Dump "Я"'
FLAGS = (POK,READONLY,IsCOW,pPOK,UTF8)
This is a unicode string. It has the so-called 'UTF8 flag' turned on, while binary strings don't (internally, Perl 'unicode' strings are encoded in UTF-8).

2) Perl pretends that it doesn't have two different types of strings. Whenever a binary string enters a 'Unicode context' (so to say), Perl converts binary string to Unicode, with not entirely satisfactory results. Also, it sometimes try to convert Unicode strings to binary, which also doesn't work very well

$ perl -E 'binmode STDOUT, ":encoding(UTF-8)"; say "Я"'
Я
Binary string "Я" got mangled in Unicode context.
$ perl -E 'use utf8; my $x = "Я"; no utf8; my $y = "Я"; say $x . $y'
Wide character in say at -e line 1.
ЯЯ
Unicode string $x was concatenated with binary string $y, and $y was 'upgraded' to Unicode. At least, we got a warning...
$ perl -wE 'use utf8; my $x = ""; no utf8; my $y = ""; say $x . $y'
Where's my warning, Perl?... And what happened with $x???

3) Perl thinks that all binary strings (those without UTF-8 flag) are encoded in Latin-1. Whenever it sees fit, it converts them to Unicode. And vice versa.

c2 bb becomes U+00C2 U+00BB. That is, "" becomes "»" (from Latin-1 to Unicode). "" becomes "�" (from Unicode to Latin-1, which cannot be displayed on my terminal).

4) To make things more interesting, Perl doesn't always turn UTF-8 flag on

$ perl -MDevel::Peek -E 'use utf8; Dump "This is America!"'
FLAGS = (POK,READONLY,IsCOW,pPOK)

Conclusion: to use Perl, you must either be an American, or an expert in Unicode and Perl internals. Well, you seem to be an American, Jim.