use bytes
pragma?decode_utf8
and encode_utf8
?UTF-8
and utf8
?
perlunitut - Perl Unicode Tutorial
The days of just flinging strings around are over. It's well established that modern programs need to be capable of communicating funny accented letters, and things like euro symbols. This means that programmers need new habits. It's easy to program Unicode capable software, but it does require discipline to do it right.
There's a lot to know about character sets, and text encodings. It's probably best to spend a full day learning all this, but the basics can be learned in minutes.
These are not the very basics, though. It is assumed that you already know the difference between bytes and characters, and realise (and accept!) that there are many different character sets and encodings, and that your program has to be explicit about them. Recommended reading is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" by Joel Spolsky, at http://joelonsoftware.com/articles/Unicode.html.
This tutorial speaks in rather absolute terms, and provides only a limited view of the wealth of character string related features that Perl has to offer. For most projects, this information will probably suffice.
It's important to set a few things straight first. This is the most important part of this tutorial. This view may conflict with other information that you may have found on the web, but that's mostly because many sources are wrong.
You may have to re-read this entire section a few times...
Unicode is a character set with room for lots of characters. The ordinal value of a character is called a code point.
There are many, many code points, but computers work with bytes, and a byte can have only 256 values. Unicode has many more characters, so you need a method to make these accessible.
Unicode is encoded using several competing encodings, of which UTF-8 is the most used. In a Unicode encoding, multiple subsequent bytes can be used to store a single code point, or simply: character.
UTF-8 is a Unicode encoding. Many people think that Unicode and UTF-8 are the same thing, but they're not. There are more Unicode encodings, but much of the world has standardized on UTF-8.
UTF-8 treats the first 128 codepoints, 0..127, the same as ASCII. They take only one byte per character. All other characters are encoded as two or more (up to six) bytes using a complex scheme. Fortunately, Perl handles this for us, so we don't have to worry about this.
Text strings, or character strings are made of characters. Bytes are irrelevant here, and so are encodings. Each character is just that: the character.
On a text string, you would do things like:
$text =~ s/foo/bar/; if ($string =~ /^\d+$/) { ... } $text = ucfirst $text; my $character_count = length $text;
The value of a character (ord
, chr
) is the corresponding Unicode code
point.
Binary strings, or byte strings are made of bytes. Here, you don't have characters, just bytes. All communication with the outside world (anything outside of your current Perl process) is done in binary.
On a binary string, you would do things like:
my (@length_content) = unpack "(V/a)*", $binary; $binary =~ s/\x00\x0F/\xFF\xF0/; # for the brave :) print {$fh} $binary; my $byte_count = length $binary;
Encoding (as a verb) is the conversion from text to binary. To encode,
you have to supply the target encoding, for example iso-8859-1
or UTF-8
.
Some encodings, like the iso-8859
("latin") range, do not support the full
Unicode standard; characters that can't be represented are lost in the
conversion.
Decoding is the conversion from binary to text. To decode, you have to know what encoding was used during the encoding phase. And most of all, it must be something decodable. It doesn't make much sense to decode a PNG image into a text string.
Perl has an internal format, an encoding that it uses to encode text strings so it can store them in memory. All text strings are in this internal format. In fact, text strings are never in any other format!
You shouldn't worry about what this format is, because conversion is automatically done when you decode or encode.
Add to your standard heading the following line:
use Encode qw(encode decode);
Or, if you're lazy, just:
use Encode;
The typical input/output flow of a program is:
1. Receive and decode 2. Process 3. Encode and output
If your input is binary, and is supposed to remain binary, you shouldn't decode it to a text string, of course. But in all other cases, you should decode it.
Decoding can't happen reliably if you don't know how the data was encoded. If you get to choose, it's a good idea to standardize on UTF-8.
my $foo = decode('UTF-8', get 'http://example.com/'); my $bar = decode('ISO-8859-1', readline STDIN); my $xyzzy = decode('Windows-1251', $cgi->param('foo'));
Processing happens as you knew before. The only difference is that you're now
using characters instead of bytes. That's very useful if you use things like
substr
, or length
.
It's important to realize that there are no bytes in a text string. Of course, Perl has its internal encoding to store the string in memory, but ignore that. If you have to do anything with the number of bytes, it's probably best to move that part to step 3, just after you've encoded the string. Then you know exactly how many bytes it will be in the destination string.
The syntax for encoding text strings to binary strings is as simple as decoding:
$body = encode('UTF-8', $body);
If you needed to know the length of the string in bytes, now's the perfect time
for that. Because $body
is now a byte string, length
will report the
number of bytes, instead of the number of characters. The number of
characters is no longer known, because characters only exist in text strings.
my $byte_count = length $body;
And if the protocol you're using supports a way of letting the recipient know
which character encoding you used, please help the receiving end by using that
feature! For example, E-mail and HTTP support MIME headers, so you can use the
Content-Type
header. They can also have Content-Length
to indicate the
number of bytes, which is always a good idea to supply if the number is
known.
"Content-Type: text/plain; charset=UTF-8", "Content-Length: $byte_count"
No, Perl has an abstracted interface for all supported character encodings, so
this is actually a generic Encode
tutorial. But many people think that
Unicode is special and magical, and I didn't want to disappoint them, so I
decided to call this document a Unicode tutorial.
Well, apart from a bare binmode $fh
, you shouldn't treat them specially.
(The binmode is needed because otherwise Perl may convert line endings on Win32
systems.)
Be careful, though, to never combine text strings with binary strings. If you need text in a binary stream, encode your text strings first using the appropriate encoding, then join them with binary strings. See also: "What if I don't encode?".
Please, unless you're hacking the internals, or debugging weirdness, don't
think about the UTF-8 flag at all. That means that you very probably shouldn't
use is_utf8
, _utf8_on
or _utf8_off
at all.
Perl's internal format happens to be UTF-8. Unfortunately, Perl can't keep a secret, so everyone knows about this. That is the source of much confusion. It's better to pretend that the internal format is some unknown encoding, and that you always have to encode and decode explicitly.
Whenever you're communicating with anything that is external to your perl process, like a database, a text file, a socket, or another program. Even if the thing you're communicating with is also written in Perl.
Whenever your encoded, binary string is used together with a text string, Perl
will assume that your binary string was encoded with ISO-8859-1, also known as
latin-1. If it wasn't latin-1, then your data is unpleasantly converted. For
example, if it was UTF-8, the individual bytes of multibyte characters are seen
as separate characters, and then again converted to UTF-8. Such double encoding
can be compared to double HTML encoding (>
), or double URI encoding
(%253E
).
This silent implicit decoding is known as "upgrading". That may sound positive, but it's best to avoid it.
Your text string will be sent using the bytes in Perl's internal format. In some cases, Perl will warn you that you're doing something wrong, with a friendly warning:
Wide character in print at example.pl line 2.
Because the internal format is often UTF-8, these bugs are hard to spot, because UTF-8 is usually the encoding you wanted! But don't be lazy, and don't use the fact that Perl's internal format is UTF-8 to your advantage. Encode explicitly to avoid weird bugs, and to show to maintenance programmers that you thought this through.
If all data that comes from a certain handle is encoded in exactly the same
way, you can tell the PerlIO system to automatically decode everything, with
the encoding
layer. If you do this, you can't accidentally forget to decode
or encode anymore, on things that use the layered handle.
You can provide this layer when open
ing the file:
open my $fh, '>:encoding(UTF-8)', $filename; # auto encoding on write open my $fh, '<:encoding(UTF-8)', $filename; # auto decoding on read
Or if you already have an open filehandle:
binmode $fh, ':encoding(UTF-8)';
Some database drivers for DBI can also automatically encode and decode, but that is typically limited to the UTF-8 encoding, because they cheat.
Well, because Perl's internal format is UTF-8, you can just skip the encoding or decoding step, and manipulate the UTF-8 flag directly.
Instead of :encoding(UTF-8)
, you can simply use :utf8
. This is widely
accepted as good behavior.
Instead of decode
and encode
, you could use _utf8_on
and _utf8_off
.
But this is, contrary to :utf8
, considered bad style.
There are some shortcuts for oneliners; see -C
in perlrun.
Do whatever you can to find out, and if you have to: guess. (Don't forget to document your guess with a comment.)
You could open the document in a web browser, and change the character set or character encoding until you can visually confirm that all characters look the way they should.
There is no way to reliably detect the encoding automatically, so if people keep sending you data without charset indication, you may have to educate them.
Yes, you can! If your sources are UTF-8 encoded, you can indicate that with the
use utf8
pragma.
use utf8;
This doesn't do anything to your input, or to your output. It only influences
the way your sources are read. You can use Unicode in string literals, in
identifiers (but they still have to be "word characters" according to \w
),
and even in custom delimiters.
No, Data::Dumper's Unicode abilities are as they should be. There have been
some complaints that it should restore the UTF-8 flag when the data is read
again with eval
. However, you should really not look at the flag, and
nothing indicates that Data::Dumper should break this rule.
Here's what happens: when Perl reads in a string literal, it sticks to 8 bit encoding as long as it can. (But perhaps originally it was internally encoded as UTF-8, when you dumped it.) When it has to give that up because other characters are added to the text string, it silently upgrades the string to UTF-8.
If you properly encode your strings for output, none of this is of your
concern, and you can just eval
dumped data as always.
You can't. Some use the UTF-8 flag for this, but that's misuse, and makes well behaved modules like Data::Dumper look bad. The flag is useless for this purpose, because it's off when an 8 bit encoding (by default ISO-8859-1) is used to store the string.
This is something you, the programmer, has to keep track of; sorry. You could consider adopting a kind of "Hungarian notation" to help with this.
By first converting the FOO-encoded byte string to a text string, and then the text string to a BAR-encoded byte string:
my $text_string = decode('FOO', $foo_string); my $bar_string = encode('BAR', $text_string);
or by skipping the text string part, and going directly from one binary encoding to the other:
use Encode qw(from_to); from_to($string, 'FOO', 'BAR'); # changes contents of $string
or by letting automatic decoding and encoding do all the work:
open my $foofh, '<:encoding(FOO)', 'example.foo.txt'; open my $barfh, '>:encoding(BAR)', 'example.bar.txt'; print { $barfh } $_ while <$foofh>;
use bytes
pragma?Don't use it. It makes no sense to deal with bytes in a text string, and it makes no sense to deal with characters in a byte string. Do the proper conversions (by decoding/encoding), and things will work out well: you get character counts for decoded data, and byte counts for encoded data.
use bytes
is usually a failed attempt to do something useful. Just forget
about it.
decode_utf8
and encode_utf8
?These are alternate syntaxes for decode('utf8', ...)
and encode('utf8',
...)
.
UTF-8
and utf8
?UTF-8
is the official standard. utf8
is Perl's way of being liberal in
what it accepts. If you have to communicate with things that aren't so liberal,
you may want to consider using UTF-8
. If you have to communicate with things
that are too liberal, you may have to use utf8
. The full explanation is in
Encode.
UTF-8
is internally known as utf-8-strict
. This tutorial uses UTF-8
consistently, even where utf8 is actually used internally, because the
distinction can be hard to make, and is mostly irrelevant.
Okay, if you insist: the "internal format" is utf8, not UTF-8. (When it's not some other encoding.)
It's good that you lost track, because you shouldn't depend on the internal format being any specific encoding. But since you asked: by default, the internal format is either ISO-8859-1 (latin-1), or utf8, depending on the history of the string.
Perl knows how it stored the string internally, and will use that knowledge
when you encode
. In other words: don't try to find out what the internal
encoding for a certain string is, but instead just encode it into the encoding
that you want.
To find out which character encodings your Perl supports, run:
perl -MEncode -le "print for Encode->encodings(':all')"
Well, if you can, upgrade to the most recent, but certainly 5.8.1
or newer.
This tutorial is based on the status quo as of 5.8.7
.
You should also check your modules, and upgrade them if necessary. For example, HTML::Entities requires version >= 1.32 to function correctly, even though the changelog is silent about this.
Decode everything you receive, encode everything you send out. (If it's text data.)
Thanks to Johan Vromans from Squirrel Consultancy. His UTF-8 rants during the Amsterdam Perl Mongers meetings got me interested and determined to find out how to use character encodings in Perl in ways that don't break easily.
Thanks to Gerard Goossen from TTY. His presentation "UTF-8 in the wild" (Dutch Perl Workshop 2006) inspired me to publish my thoughts and write this tutorial.
Thanks to the people who asked about this kind of stuff in several Perl IRC channels, and have constantly reminded me that a simpler explanation was needed.
Thanks to the people who reviewed this document for me, before it went public. They are: Benjamin Smith, Jan-Pieter Cornet, Johan Vromans, Lukas Mai, Nathan Gray.
Juerd Waalboer <juerd@cpan.org>
perlunicode, perluniintro, Encode