1encoding(3pm) Perl Programmers Reference Guide encoding(3pm)
2
3
4
6 encoding - allows you to write your script in non-ascii or non-utf8
7
9 use encoding "greek"; # Perl like Greek to you?
10 use encoding "euc-jp"; # Jperl!
11
12 # or you can even do this if your shell supports your native encoding
13
14 perl -Mencoding=latin2 -e'...' # Feeling centrally European?
15 perl -Mencoding=euc-kr -e'...' # Or Korean?
16
17 # more control
18
19 # A simple euc-cn => utf-8 converter
20 use encoding "euc-cn", STDOUT => "utf8"; while(<>){print};
21
22 # "no encoding;" supported (but not scoped!)
23 no encoding;
24
25 # an alternate way, Filter
26 use encoding "euc-jp", Filter=>1;
27 # now you can use kanji identifiers -- in euc-jp!
28
29 # switch on locale -
30 # note that this probably means that unless you have a complete control
31 # over the environments the application is ever going to be run, you should
32 # NOT use the feature of encoding pragma allowing you to write your script
33 # in any recognized encoding because changing locale settings will wreck
34 # the script; you can of course still use the other features of the pragma.
35 use encoding ':locale';
36
38 Let's start with a bit of history: Perl 5.6.0 introduced Unicode
39 support. You could apply "substr()" and regexes even to complex CJK
40 characters -- so long as the script was written in UTF-8. But back
41 then, text editors that supported UTF-8 were still rare and many users
42 instead chose to write scripts in legacy encodings, giving up a whole
43 new feature of Perl 5.6.
44
45 Rewind to the future: starting from perl 5.8.0 with the encoding
46 pragma, you can write your script in any encoding you like (so long as
47 the "Encode" module supports it) and still enjoy Unicode support. This
48 pragma achieves that by doing the following:
49
50 · Internally converts all literals ("q//,qq//,qr//,qw///, qx//") from
51 the encoding specified to utf8. In Perl 5.8.1 and later, literals
52 in "tr///" and "DATA" pseudo-filehandle are also converted.
53
54 · Changing PerlIO layers of "STDIN" and "STDOUT" to the encoding
55 specified.
56
57 Literal Conversions
58 You can write code in EUC-JP as follows:
59
60 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
61 #<-char-><-char-> # 4 octets
62 s/\bCamel\b/$Rakuda/;
63
64 And with "use encoding "euc-jp"" in effect, it is the same thing as the
65 code in UTF-8:
66
67 my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
68 s/\bCamel\b/$Rakuda/;
69
70 PerlIO layers for "STD(IN|OUT)"
71 The encoding pragma also modifies the filehandle layers of STDIN and
72 STDOUT to the specified encoding. Therefore,
73
74 use encoding "euc-jp";
75 my $message = "Camel is the symbol of perl.\n";
76 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
77 $message =~ s/\bCamel\b/$Rakuda/;
78 print $message;
79
80 Will print "\xF1\xD1\xF1\xCC is the symbol of perl.\n", not
81 "\x{99F1}\x{99DD} is the symbol of perl.\n".
82
83 You can override this by giving extra arguments; see below.
84
85 Implicit upgrading for byte strings
86 By default, if strings operating under byte semantics and strings with
87 Unicode character data are concatenated, the new string will be created
88 by decoding the byte strings as ISO 8859-1 (Latin-1).
89
90 The encoding pragma changes this to use the specified encoding instead.
91 For example:
92
93 use encoding 'utf8';
94 my $string = chr(20000); # a Unicode string
95 utf8::encode($string); # now it's a UTF-8 encoded byte string
96 # concatenate with another Unicode string
97 print length($string . chr(20000));
98
99 Will print 2, because $string is upgraded as UTF-8. Without "use
100 encoding 'utf8';", it will print 4 instead, since $string is three
101 octets when interpreted as Latin-1.
102
103 Side effects
104 If the "encoding" pragma is in scope then the lengths returned are
105 calculated from the length of $/ in Unicode characters, which is not
106 always the same as the length of $/ in the native encoding.
107
108 This pragma affects utf8::upgrade, but not utf8::downgrade.
109
111 Some of the features offered by this pragma requires perl 5.8.1. Most
112 of these are done by Inaba Hiroto. Any other features and changes are
113 good for 5.8.0.
114
115 "NON-EUC" doublebyte encodings
116 Because perl needs to parse script before applying this pragma,
117 such encodings as Shift_JIS and Big-5 that may contain '\'
118 (BACKSLASH; \x5c) in the second byte fails because the second byte
119 may accidentally escape the quoting character that follows. Perl
120 5.8.1 or later fixes this problem.
121
122 tr//
123 "tr//" was overlooked by Perl 5 porters when they released perl
124 5.8.0 See the section below for details.
125
126 DATA pseudo-filehandle
127 Another feature that was overlooked was "DATA".
128
130 use encoding [ENCNAME] ;
131 Sets the script encoding to ENCNAME. And unless ${^UNICODE} exists
132 and non-zero, PerlIO layers of STDIN and STDOUT are set to
133 ":encoding(ENCNAME)".
134
135 Note that STDERR WILL NOT be changed.
136
137 Also note that non-STD file handles remain unaffected. Use "use
138 open" or "binmode" to change layers of those.
139
140 If no encoding is specified, the environment variable PERL_ENCODING
141 is consulted. If no encoding can be found, the error "Unknown
142 encoding 'ENCNAME'" will be thrown.
143
144 use encoding ENCNAME [ STDIN => ENCNAME_IN ...] ;
145 You can also individually set encodings of STDIN and STDOUT via the
146 "STDIN => ENCNAME" form. In this case, you cannot omit the first
147 ENCNAME. "STDIN => undef" turns the IO transcoding completely off.
148
149 When ${^UNICODE} exists and non-zero, these options will completely
150 ignored. ${^UNICODE} is a variable introduced in perl 5.8.1. See
151 perlrun see "${^UNICODE}" in perlvar and "-C" in perlrun for
152 details (perl 5.8.1 and later).
153
154 use encoding ENCNAME Filter=>1;
155 This turns the encoding pragma into a source filter. While the
156 default approach just decodes interpolated literals (in qq() and
157 qr()), this will apply a source filter to the entire source code.
158 See "The Filter Option" below for details.
159
160 no encoding;
161 Unsets the script encoding. The layers of STDIN, STDOUT are reset
162 to ":raw" (the default unprocessed raw stream of bytes).
163
165 The magic of "use encoding" is not applied to the names of identifiers.
166 In order to make "${"\x{4eba}"}++" ($human++, where human is a single
167 Han ideograph) work, you still need to write your script in UTF-8 -- or
168 use a source filter. That's what 'Filter=>1' does.
169
170 What does this mean? Your source code behaves as if it is written in
171 UTF-8 with 'use utf8' in effect. So even if your editor only supports
172 Shift_JIS, for example, you can still try examples in Chapter 15 of
173 "Programming Perl, 3rd Ed.". For instance, you can use UTF-8
174 identifiers.
175
176 This option is significantly slower and (as of this writing) non-ASCII
177 identifiers are not very stable WITHOUT this option and with the source
178 code written in UTF-8.
179
180 Filter-related changes at Encode version 1.87
181 · The Filter option now sets STDIN and STDOUT like non-filter
182 options. And "STDIN=>ENCODING" and "STDOUT=>ENCODING" work like
183 non-filter version.
184
185 · "use utf8" is implicitly declared so you no longer have to "use
186 utf8" to "${"\x{4eba}"}++".
187
189 NOT SCOPED
190 The pragma is a per script, not a per block lexical. Only the last
191 "use encoding" or "no encoding" matters, and it affects the whole
192 script. However, the <no encoding> pragma is supported and use
193 encoding can appear as many times as you want in a given script. The
194 multiple use of this pragma is discouraged.
195
196 By the same reason, the use this pragma inside modules is also
197 discouraged (though not as strongly discouraged as the case above. See
198 below).
199
200 If you still have to write a module with this pragma, be very careful
201 of the load order. See the codes below;
202
203 # called module
204 package Module_IN_BAR;
205 use encoding "bar";
206 # stuff in "bar" encoding here
207 1;
208
209 # caller script
210 use encoding "foo"
211 use Module_IN_BAR;
212 # surprise! use encoding "bar" is in effect.
213
214 The best way to avoid this oddity is to use this pragma RIGHT AFTER
215 other modules are loaded. i.e.
216
217 use Module_IN_BAR;
218 use encoding "foo";
219
220 DO NOT MIX MULTIPLE ENCODINGS
221 Notice that only literals (string or regular expression) having only
222 legacy code points are affected: if you mix data like this
223
224 \xDF\x{100}
225
226 the data is assumed to be in (Latin 1 and) Unicode, not in your native
227 encoding. In other words, this will match in "greek":
228
229 "\xDF" =~ /\x{3af}/
230
231 but this will not
232
233 "\xDF\x{100}" =~ /\x{3af}\x{100}/
234
235 since the "\xDF" (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on the
236 left will not be upgraded to "\x{3af}" (Unicode GREEK SMALL LETTER IOTA
237 WITH TONOS) because of the "\x{100}" on the left. You should not be
238 mixing your legacy data and Unicode in the same string.
239
240 This pragma also affects encoding of the 0x80..0xFF code point range:
241 normally characters in that range are left as eight-bit bytes (unless
242 they are combined with characters with code points 0x100 or larger, in
243 which case all characters need to become UTF-8 encoded), but if the
244 "encoding" pragma is present, even the 0x80..0xFF range always gets
245 UTF-8 encoded.
246
247 After all, the best thing about this pragma is that you don't have to
248 resort to \x{....} just to spell your name in a native encoding. So
249 feel free to put your strings in your encoding in quotes and regexes.
250
251 tr/// with ranges
252 The encoding pragma works by decoding string literals in
253 "q//,qq//,qr//,qw///, qx//" and so forth. In perl 5.8.0, this does not
254 apply to "tr///". Therefore,
255
256 use encoding 'euc-jp';
257 #....
258 $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
259 # -------- -------- -------- --------
260
261 Does not work as
262
263 $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;
264
265 Legend of characters above
266 utf8 euc-jp charnames::viacode()
267 -----------------------------------------
268 \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
269 \x{3093} \xA4\xF3 HIRAGANA LETTER N
270 \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
271 \x{30f3} \xA5\xF3 KATAKANA LETTER N
272
273 This counterintuitive behavior has been fixed in perl 5.8.1.
274
275 workaround to tr///;
276
277 In perl 5.8.0, you can work around as follows;
278
279 use encoding 'euc-jp';
280 # ....
281 eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };
282
283 Note the "tr//" expression is surrounded by "qq{}". The idea behind is
284 the same as classic idiom that makes "tr///" 'interpolate'.
285
286 tr/$from/$to/; # wrong!
287 eval qq{ tr/$from/$to/ }; # workaround.
288
289 Nevertheless, in case of encoding pragma even "q//" is affected so
290 "tr///" not being decoded was obviously against the will of Perl5
291 Porters so it has been fixed in Perl 5.8.1 or later.
292
294 use encoding "iso 8859-7";
295
296 # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.
297
298 $a = "\xDF";
299 $b = "\x{100}";
300
301 printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
302
303 $c = $a . $b;
304
305 # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
306
307 # chr() is affected, and ...
308
309 print "mega\n" if ord(chr(0xdf)) == 0x3af;
310
311 # ... ord() is affected by the encoding pragma ...
312
313 print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
314
315 # ... as are eq and cmp ...
316
317 print "peta\n" if "\x{3af}" eq pack("C", 0xdf);
318 print "exa\n" if "\x{3af}" cmp pack("C", 0xdf) == 0;
319
320 # ... but pack/unpack C are not affected, in case you still
321 # want to go back to your native encoding
322
323 print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
324
326 literals in regex that are longer than 127 bytes
327 For native multibyte encodings (either fixed or variable length),
328 the current implementation of the regular expressions may introduce
329 recoding errors for regular expression literals longer than 127
330 bytes.
331
332 EBCDIC
333 The encoding pragma is not supported on EBCDIC platforms. (Porters
334 who are willing and able to remove this limitation are welcome.)
335
336 format
337 This pragma doesn't work well with format because PerlIO does not
338 get along very well with it. When format contains non-ascii
339 characters it prints funny or gets "wide character warnings". To
340 understand it, try the code below.
341
342 # Save this one in utf8
343 # replace *non-ascii* with a non-ascii string
344 my $camel;
345 format STDOUT =
346 *non-ascii*@>>>>>>>
347 $camel
348 .
349 $camel = "*non-ascii*";
350 binmode(STDOUT=>':encoding(utf8)'); # bang!
351 write; # funny
352 print $camel, "\n"; # fine
353
354 Without binmode this happens to work but without binmode, print()
355 fails instead of write().
356
357 At any rate, the very use of format is questionable when it comes
358 to unicode characters since you have to consider such things as
359 character width (i.e. double-width for ideographs) and directions
360 (i.e. BIDI for Arabic and Hebrew).
361
362 Thread safety
363 "use encoding ..." is not thread-safe (i.e., do not use in threaded
364 applications).
365
366 The Logic of :locale
367 The logic of ":locale" is as follows:
368
369 1. If the platform supports the langinfo(CODESET) interface, the
370 codeset returned is used as the default encoding for the open
371 pragma.
372
373 2. If 1. didn't work but we are under the locale pragma, the
374 environment variables LC_ALL and LANG (in that order) are matched
375 for encodings (the part after ".", if any), and if any found, that
376 is used as the default encoding for the open pragma.
377
378 3. If 1. and 2. didn't work, the environment variables LC_ALL and LANG
379 (in that order) are matched for anything looking like UTF-8, and if
380 any found, ":utf8" is used as the default encoding for the open
381 pragma.
382
383 If your locale environment variables (LC_ALL, LC_CTYPE, LANG) contain
384 the strings 'UTF-8' or 'UTF8' (case-insensitive matching), the default
385 encoding of your STDIN, STDOUT, and STDERR, and of any subsequent file
386 open, is UTF-8.
387
389 This pragma first appeared in Perl 5.8.0. For features that require
390 5.8.1 and better, see above.
391
392 The ":locale" subpragma was implemented in 2.01, or Perl 5.8.6.
393
395 perlunicode, Encode, open, Filter::Util::Call,
396
397 Ch. 15 of "Programming Perl (3rd Edition)" by Larry Wall, Tom
398 Christiansen, Jon Orwant; O'Reilly & Associates; ISBN 0-596-00027-8
399
400
401
402perl v5.12.4 2011-06-01 encoding(3pm)