Localize $! in splainthis() too. (see bug #41717)
[p5sagit/p5-mst-13.2.git] / pod / perlunitut.pod
CommitLineData
aadaa455 1=head1 NAME
2
3perlunitut - Perl Unicode Tutorial
4
5=head1 DESCRIPTION
6
7The days of just flinging strings around are over. It's well established that
8modern programs need to be capable of communicating funny accented letters, and
9things like euro symbols. This means that programmers need new habits. It's
10easy to program Unicode capable software, but it does require discipline to do
11it right.
12
13There's a lot to know about character sets, and text encodings. It's probably
14best to spend a full day learning all this, but the basics can be learned in
15minutes.
16
17These are not the very basics, though. It is assumed that you already
18know the difference between bytes and characters, and realise (and accept!)
19that there are many different character sets and encodings, and that your
20program has to be explicit about them. Recommended reading is "The Absolute
21Minimum Every Software Developer Absolutely, Positively Must Know About Unicode
22and Character Sets (No Excuses!)" by Joel Spolsky, at
23L<http://joelonsoftware.com/articles/Unicode.html>.
24
25This tutorial speaks in rather absolute terms, and provides only a limited view
26of the wealth of character string related features that Perl has to offer. For
27most projects, this information will probably suffice.
28
29=head2 Definitions
30
31It's important to set a few things straight first. This is the most important
32part of this tutorial. This view may conflict with other information that you
33may have found on the web, but that's mostly because many sources are wrong.
34
35You may have to re-read this entire section a few times...
36
37=head3 Unicode
38
39B<Unicode> is a character set with room for lots of characters. The ordinal
40value of a character is called a B<code point>.
41
42There are many, many code points, but computers work with bytes, and a byte can
43have only 256 values. Unicode has many more characters, so you need a method
44to make these accessible.
45
46Unicode is encoded using several competing encodings, of which UTF-8 is the
47most used. In a Unicode encoding, multiple subsequent bytes can be used to
48store a single code point, or simply: character.
49
50=head3 UTF-8
51
52B<UTF-8> is a Unicode encoding. Many people think that Unicode and UTF-8 are
53the same thing, but they're not. There are more Unicode encodings, but much of
54the world has standardized on UTF-8.
55
56UTF-8 treats the first 128 codepoints, 0..127, the same as ASCII. They take
57only one byte per character. All other characters are encoded as two or more
58(up to six) bytes using a complex scheme. Fortunately, Perl handles this for
59us, so we don't have to worry about this.
60
61=head3 Text strings (character strings)
62
63B<Text strings>, or B<character strings> are made of characters. Bytes are
64irrelevant here, and so are encodings. Each character is just that: the
65character.
66
67On a text string, you would do things like:
68
69 $text =~ s/foo/bar/;
70 if ($string =~ /^\d+$/) { ... }
71 $text = ucfirst $text;
72 my $character_count = length $text;
73
74The value of a character (C<ord>, C<chr>) is the corresponding Unicode code
75point.
76
77=head3 Binary strings (byte strings)
78
79B<Binary strings>, or B<byte strings> are made of bytes. Here, you don't have
80characters, just bytes. All communication with the outside world (anything
81outside of your current Perl process) is done in binary.
82
83On a binary string, you would do things like:
84
85 my (@length_content) = unpack "(V/a)*", $binary;
86 $binary =~ s/\x00\x0F/\xFF\xF0/; # for the brave :)
87 print {$fh} $binary;
88 my $byte_count = length $binary;
89
90=head3 Encoding
91
92B<Encoding> (as a verb) is the conversion from I<text> to I<binary>. To encode,
93you have to supply the target encoding, for example C<iso-8859-1> or C<UTF-8>.
94Some encodings, like the C<iso-8859> ("latin") range, do not support the full
95Unicode standard; characters that can't be represented are lost in the
96conversion.
97
98=head3 Decoding
99
100B<Decoding> is the conversion from I<binary> to I<text>. To decode, you have to
101know what encoding was used during the encoding phase. And most of all, it must
102be something decodable. It doesn't make much sense to decode a PNG image into a
103text string.
104
105=head3 Internal format
106
107Perl has an B<internal format>, an encoding that it uses to encode text strings
108so it can store them in memory. All text strings are in this internal format.
109In fact, text strings are never in any other format!
110
111You shouldn't worry about what this format is, because conversion is
112automatically done when you decode or encode.
113
114=head2 Your new toolkit
115
116Add to your standard heading the following line:
117
118 use Encode qw(encode decode);
119
120Or, if you're lazy, just:
121
122 use Encode;
123
124=head2 I/O flow (the actual 5 minute tutorial)
125
126The typical input/output flow of a program is:
127
128 1. Receive and decode
129 2. Process
130 3. Encode and output
131
132If your input is binary, and is supposed to remain binary, you shouldn't decode
133it to a text string, of course. But in all other cases, you should decode it.
134
135Decoding can't happen reliably if you don't know how the data was encoded. If
136you get to choose, it's a good idea to standardize on UTF-8.
137
138 my $foo = decode('UTF-8', get 'http://example.com/');
139 my $bar = decode('ISO-8859-1', readline STDIN);
140 my $xyzzy = decode('Windows-1251', $cgi->param('foo'));
141
142Processing happens as you knew before. The only difference is that you're now
143using characters instead of bytes. That's very useful if you use things like
144C<substr>, or C<length>.
145
146It's important to realize that there are no bytes in a text string. Of course,
147Perl has its internal encoding to store the string in memory, but ignore that.
148If you have to do anything with the number of bytes, it's probably best to move
149that part to step 3, just after you've encoded the string. Then you know
150exactly how many bytes it will be in the destination string.
151
152The syntax for encoding text strings to binary strings is as simple as decoding:
153
154 $body = encode('UTF-8', $body);
155
156If you needed to know the length of the string in bytes, now's the perfect time
157for that. Because C<$body> is now a byte string, C<length> will report the
158number of bytes, instead of the number of characters. The number of
159characters is no longer known, because characters only exist in text strings.
160
161 my $byte_count = length $body;
162
163And if the protocol you're using supports a way of letting the recipient know
164which character encoding you used, please help the receiving end by using that
165feature! For example, E-mail and HTTP support MIME headers, so you can use the
166C<Content-Type> header. They can also have C<Content-Length> to indicate the
167number of I<bytes>, which is always a good idea to supply if the number is
168known.
169
170 "Content-Type: text/plain; charset=UTF-8",
171 "Content-Length: $byte_count"
172
173=head2 Q and A
174
175=head3 This isn't really a Unicode tutorial, is it?
176
177No, Perl has an abstracted interface for all supported character encodings, so
178this is actually a generic C<Encode> tutorial. But many people think that
179Unicode is special and magical, and I didn't want to disappoint them, so I
180decided to call this document a Unicode tutorial.
181
182=head3 What about binary data, like images?
183
184Well, apart from a bare C<binmode $fh>, you shouldn't treat them specially.
185(The binmode is needed because otherwise Perl may convert line endings on Win32
186systems.)
187
188Be careful, though, to never combine text strings with binary strings. If you
189need text in a binary stream, encode your text strings first using the
190appropriate encoding, then join them with binary strings. See also: "What if I
191don't encode?".
192
193=head3 What about the UTF-8 flag?
194
195Please, unless you're hacking the internals, or debugging weirdness, don't
196think about the UTF-8 flag at all. That means that you very probably shouldn't
197use C<is_utf8>, C<_utf8_on> or C<_utf8_off> at all.
198
199Perl's internal format happens to be UTF-8. Unfortunately, Perl can't keep a
200secret, so everyone knows about this. That is the source of much confusion.
201It's better to pretend that the internal format is some unknown encoding,
202and that you always have to encode and decode explicitly.
203
204=head3 When should I decode or encode?
205
206Whenever you're communicating with anything that is external to your perl
207process, like a database, a text file, a socket, or another program. Even if
208the thing you're communicating with is also written in Perl.
209
210=head3 What if I don't decode?
211
212Whenever your encoded, binary string is used together with a text string, Perl
213will assume that your binary string was encoded with ISO-8859-1, also known as
214latin-1. If it wasn't latin-1, then your data is unpleasantly converted. For
215example, if it was UTF-8, the individual bytes of multibyte characters are seen
216as separate characters, and then again converted to UTF-8. Such double encoding
217can be compared to double HTML encoding (C<&amp;gt;>), or double URI encoding
218(C<%253E>).
219
220This silent implicit decoding is known as "upgrading". That may sound
221positive, but it's best to avoid it.
222
223=head3 What if I don't encode?
224
225Your text string will be sent using the bytes in Perl's internal format. In
226some cases, Perl will warn you that you're doing something wrong, with a
227friendly warning:
228
229 Wide character in print at example.pl line 2.
230
231Because the internal format is often UTF-8, these bugs are hard to spot,
232because UTF-8 is usually the encoding you wanted! But don't be lazy, and don't
233use the fact that Perl's internal format is UTF-8 to your advantage. Encode
234explicitly to avoid weird bugs, and to show to maintenance programmers that you
235thought this through.
236
237=head3 Is there a way to automatically decode or encode?
238
239If all data that comes from a certain handle is encoded in exactly the same
240way, you can tell the PerlIO system to automatically decode everything, with
241the C<encoding> layer. If you do this, you can't accidentally forget to decode
242or encode anymore, on things that use the layered handle.
243
244You can provide this layer when C<open>ing the file:
245
246 open my $fh, '>:encoding(UTF-8)', $filename; # auto encoding on write
247 open my $fh, '<:encoding(UTF-8)', $filename; # auto decoding on read
248
249Or if you already have an open filehandle:
250
251 binmode $fh, ':encoding(UTF-8)';
252
253Some database drivers for DBI can also automatically encode and decode, but
254that is typically limited to the UTF-8 encoding, because they cheat.
255
256=head3 Cheat?! Tell me, how can I cheat?
257
258Well, because Perl's internal format is UTF-8, you can just skip the encoding
259or decoding step, and manipulate the UTF-8 flag directly.
260
261Instead of C<:encoding(UTF-8)>, you can simply use C<:utf8>. This is widely
262accepted as good behavior.
263
264Instead of C<decode> and C<encode>, you could use C<_utf8_on> and C<_utf8_off>.
265But this is, contrary to C<:utf8>, considered bad style.
266
267There are some shortcuts for oneliners; see C<-C> in L<perlrun>.
268
269=head3 What if I don't know which encoding was used?
270
271Do whatever you can to find out, and if you have to: guess. (Don't forget to
272document your guess with a comment.)
273
274You could open the document in a web browser, and change the character set or
275character encoding until you can visually confirm that all characters look the
276way they should.
277
278There is no way to reliably detect the encoding automatically, so if people
279keep sending you data without charset indication, you may have to educate them.
280
281=head3 Can I use Unicode in my Perl sources?
282
283Yes, you can! If your sources are UTF-8 encoded, you can indicate that with the
284C<use utf8> pragma.
285
286 use utf8;
287
288This doesn't do anything to your input, or to your output. It only influences
289the way your sources are read. You can use Unicode in string literals, in
290identifiers (but they still have to be "word characters" according to C<\w>),
291and even in custom delimiters.
292
293=head3 Data::Dumper doesn't restore the UTF-8 flag; is it broken?
294
295No, Data::Dumper's Unicode abilities are as they should be. There have been
296some complaints that it should restore the UTF-8 flag when the data is read
297again with C<eval>. However, you should really not look at the flag, and
298nothing indicates that Data::Dumper should break this rule.
299
300Here's what happens: when Perl reads in a string literal, it sticks to 8 bit
301encoding as long as it can. (But perhaps originally it was internally encoded
302as UTF-8, when you dumped it.) When it has to give that up because other
303characters are added to the text string, it silently upgrades the string to
304UTF-8.
305
306If you properly encode your strings for output, none of this is of your
307concern, and you can just C<eval> dumped data as always.
308
309=head3 How can I determine if a string is a text string or a binary string?
310
311You can't. Some use the UTF-8 flag for this, but that's misuse, and makes well
312behaved modules like Data::Dumper look bad. The flag is useless for this
313purpose, because it's off when an 8 bit encoding (by default ISO-8859-1) is
314used to store the string.
315
316This is something you, the programmer, has to keep track of; sorry. You could
317consider adopting a kind of "Hungarian notation" to help with this.
318
319=head3 How do I convert from encoding FOO to encoding BAR?
320
321By first converting the FOO-encoded byte string to a text string, and then the
322text string to a BAR-encoded byte string:
323
324 my $text_string = decode('FOO', $foo_string);
325 my $bar_string = encode('BAR', $text_string);
326
327or by skipping the text string part, and going directly from one binary
328encoding to the other:
329
330 use Encode qw(from_to);
331 from_to($string, 'FOO', 'BAR'); # changes contents of $string
332
333or by letting automatic decoding and encoding do all the work:
334
335 open my $foofh, '<:encoding(FOO)', 'example.foo.txt';
336 open my $barfh, '>:encoding(BAR)', 'example.bar.txt';
337 print { $barfh } $_ while <$foofh>;
338
339=head3 What about the C<use bytes> pragma?
340
341Don't use it. It makes no sense to deal with bytes in a text string, and it
342makes no sense to deal with characters in a byte string. Do the proper
343conversions (by decoding/encoding), and things will work out well: you get
344character counts for decoded data, and byte counts for encoded data.
345
346C<use bytes> is usually a failed attempt to do something useful. Just forget
347about it.
348
349=head3 What are C<decode_utf8> and C<encode_utf8>?
350
351These are alternate syntaxes for C<decode('utf8', ...)> and C<encode('utf8',
352...)>.
353
354=head3 What's the difference between C<UTF-8> and C<utf8>?
355
356C<UTF-8> is the official standard. C<utf8> is Perl's way of being liberal in
357what it accepts. If you have to communicate with things that aren't so liberal,
358you may want to consider using C<UTF-8>. If you have to communicate with things
359that are too liberal, you may have to use C<utf8>. The full explanation is in
360L<Encode>.
361
362C<UTF-8> is internally known as C<utf-8-strict>. This tutorial uses UTF-8
363consistently, even where utf8 is actually used internally, because the
364distinction can be hard to make, and is mostly irrelevant.
365
366Okay, if you insist: the "internal format" is utf8, not UTF-8. (When it's not
367some other encoding.)
368
369=head3 I lost track; what encoding is the internal format really?
370
371It's good that you lost track, because you shouldn't depend on the internal
372format being any specific encoding. But since you asked: by default, the
373internal format is either ISO-8859-1 (latin-1), or utf8, depending on the
374history of the string.
375
376Perl knows how it stored the string internally, and will use that knowledge
377when you C<encode>. In other words: don't try to find out what the internal
378encoding for a certain string is, but instead just encode it into the encoding
379that you want.
380
381=head3 What character encodings does Perl support?
382
383To find out which character encodings your Perl supports, run:
384
385 perl -MEncode -le "print for Encode->encodings(':all')"
386
387=head3 Which version of perl should I use?
388
389Well, if you can, upgrade to the most recent, but certainly C<5.8.1> or newer.
390This tutorial is based on the status quo as of C<5.8.7>.
391
392You should also check your modules, and upgrade them if necessary. For example,
393HTML::Entities requires version >= 1.32 to function correctly, even though the
394changelog is silent about this.
395
396=head1 SUMMARY
397
398Decode everything you receive, encode everything you send out. (If it's text
399data.)
400
401=head1 ACKNOWLEDGEMENTS
402
403Thanks to Johan Vromans from Squirrel Consultancy. His UTF-8 rants during the
404Amsterdam Perl Mongers meetings got me interested and determined to find out
405how to use character encodings in Perl in ways that don't break easily.
406
407Thanks to Gerard Goossen from TTY. His presentation "UTF-8 in the wild" (Dutch
408Perl Workshop 2006) inspired me to publish my thoughts and write this tutorial.
409
410Thanks to the people who asked about this kind of stuff in several Perl IRC
411channels, and have constantly reminded me that a simpler explanation was
412needed.
413
414Thanks to the people who reviewed this document for me, before it went public.
415They are: Benjamin Smith, Jan-Pieter Cornet, Johan Vromans, Lukas Mai, Nathan
416Gray.
417
418=head1 AUTHOR
419
420Juerd Waalboer <juerd@cpan.org>
421
422=head1 SEE ALSO
423
424L<perlunicode>, L<perluniintro>, L<Encode>
425