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 sup‐
39 port. You could apply "substr()" and regexes even to complex CJK char‐
40 acters -- so long as the script was written in UTF-8. But back then,
41 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
59 You can write code in EUC-JP as follows:
60
61 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
62 #<-char-><-char-> # 4 octets
63 s/\bCamel\b/$Rakuda/;
64
65 And with "use encoding "euc-jp"" in effect, it is the same thing as the
66 code in UTF-8:
67
68 my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
69 s/\bCamel\b/$Rakuda/;
70
71 PerlIO layers for "STD(IN⎪OUT)"
72
73 The encoding pragma also modifies the filehandle layers of STDIN and
74 STDOUT to the specified encoding. Therefore,
75
76 use encoding "euc-jp";
77 my $message = "Camel is the symbol of perl.\n";
78 my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
79 $message =~ s/\bCamel\b/$Rakuda/;
80 print $message;
81
82 Will print "\xF1\xD1\xF1\xCC is the symbol of perl.\n", not
83 "\x{99F1}\x{99DD} is the symbol of perl.\n".
84
85 You can override this by giving extra arguments; see below.
86
87 Implicit upgrading for byte strings
88
89 By default, if strings operating under byte semantics and strings with
90 Unicode character data are concatenated, the new string will be created
91 by decoding the byte strings as ISO 8859-1 (Latin-1).
92
93 The encoding pragma changes this to use the specified encoding instead.
94 For example:
95
96 use encoding 'utf8';
97 my $string = chr(20000); # a Unicode string
98 utf8::encode($string); # now it's a UTF-8 encoded byte string
99 # concatenate with another Unicode string
100 print length($string . chr(20000));
101
102 Will print 2, because $string is upgraded as UTF-8. Without "use
103 encoding 'utf8';", it will print 4 instead, since $string is three
104 octets when interpreted as Latin-1.
105
107 Some of the features offered by this pragma requires perl 5.8.1. Most
108 of these are done by Inaba Hiroto. Any other features and changes are
109 good for 5.8.0.
110
111 "NON-EUC" doublebyte encodings
112 Because perl needs to parse script before applying this pragma,
113 such encodings as Shift_JIS and Big-5 that may contain '\' (BACK‐
114 SLASH; \x5c) in the second byte fails because the second byte may
115 accidentally escape the quoting character that follows. Perl 5.8.1
116 or later fixes this problem.
117
118 tr//
119 "tr//" was overlooked by Perl 5 porters when they released perl
120 5.8.0 See the section below for details.
121
122 DATA pseudo-filehandle
123 Another feature that was overlooked was "DATA".
124
126 use encoding [ENCNAME] ;
127 Sets the script encoding to ENCNAME. And unless ${^UNICODE} exists
128 and non-zero, PerlIO layers of STDIN and STDOUT are set to ":encod‐
129 ing(ENCNAME)".
130
131 Note that STDERR WILL NOT be changed.
132
133 Also note that non-STD file handles remain unaffected. Use "use
134 open" or "binmode" to change layers of those.
135
136 If no encoding is specified, the environment variable PERL_ENCODING
137 is consulted. If no encoding can be found, the error "Unknown
138 encoding 'ENCNAME'" will be thrown.
139
140 use encoding ENCNAME [ STDIN => ENCNAME_IN ...] ;
141 You can also individually set encodings of STDIN and STDOUT via the
142 "STDIN => ENCNAME" form. In this case, you cannot omit the first
143 ENCNAME. "STDIN => undef" turns the IO transcoding completely off.
144
145 When ${^UNICODE} exists and non-zero, these options will completely
146 ignored. ${^UNICODE} is a variable introduced in perl 5.8.1. See
147 perlrun see "${^UNICODE}" in perlvar and "-C" in perlrun for
148 details (perl 5.8.1 and later).
149
150 use encoding ENCNAME Filter=>1;
151 This turns the encoding pragma into a source filter. While the
152 default approach just decodes interpolated literals (in qq() and
153 qr()), this will apply a source filter to the entire source code.
154 See "The Filter Option" below for details.
155
156 no encoding;
157 Unsets the script encoding. The layers of STDIN, STDOUT are reset
158 to ":raw" (the default unprocessed raw stream of bytes).
159
161 The magic of "use encoding" is not applied to the names of identifiers.
162 In order to make "${"\x{4eba}"}++" ($human++, where human is a single
163 Han ideograph) work, you still need to write your script in UTF-8 -- or
164 use a source filter. That's what 'Filter=>1' does.
165
166 What does this mean? Your source code behaves as if it is written in
167 UTF-8 with 'use utf8' in effect. So even if your editor only supports
168 Shift_JIS, for example, you can still try examples in Chapter 15 of
169 "Programming Perl, 3rd Ed.". For instance, you can use UTF-8 identi‐
170 fiers.
171
172 This option is significantly slower and (as of this writing) non-ASCII
173 identifiers are not very stable WITHOUT this option and with the source
174 code written in UTF-8.
175
176 Filter-related changes at Encode version 1.87
177
178 · The Filter option now sets STDIN and STDOUT like non-filter
179 options. And "STDIN=>ENCODING" and "STDOUT=>ENCODING" work like
180 non-filter version.
181
182 · "use utf8" is implicitly declared so you no longer have to "use
183 utf8" to "${"\x{4eba}"}++".
184
186 NOT SCOPED
187
188 The pragma is a per script, not a per block lexical. Only the last
189 "use encoding" or "no encoding" matters, and it affects the whole
190 script. However, the <no encoding> pragma is supported and use encod‐
191 ing can appear as many times as you want in a given script. The multi‐
192 ple use of this pragma is discouraged.
193
194 By the same reason, the use this pragma inside modules is also discour‐
195 aged (though not as strongly discouraged as the case above. See
196 below).
197
198 If you still have to write a module with this pragma, be very careful
199 of the load order. See the codes below;
200
201 # called module
202 package Module_IN_BAR;
203 use encoding "bar";
204 # stuff in "bar" encoding here
205 1;
206
207 # caller script
208 use encoding "foo"
209 use Module_IN_BAR;
210 # surprise! use encoding "bar" is in effect.
211
212 The best way to avoid this oddity is to use this pragma RIGHT AFTER
213 other modules are loaded. i.e.
214
215 use Module_IN_BAR;
216 use encoding "foo";
217
218 DO NOT MIX MULTIPLE ENCODINGS
219
220 Notice that only literals (string or regular expression) having only
221 legacy code points are affected: if you mix data like this
222
223 \xDF\x{100}
224
225 the data is assumed to be in (Latin 1 and) Unicode, not in your native
226 encoding. In other words, this will match in "greek":
227
228 "\xDF" =~ /\x{3af}/
229
230 but this will not
231
232 "\xDF\x{100}" =~ /\x{3af}\x{100}/
233
234 since the "\xDF" (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on the
235 left will not be upgraded to "\x{3af}" (Unicode GREEK SMALL LETTER IOTA
236 WITH TONOS) because of the "\x{100}" on the left. You should not be
237 mixing your legacy data and Unicode in the same string.
238
239 This pragma also affects encoding of the 0x80..0xFF code point range:
240 normally characters in that range are left as eight-bit bytes (unless
241 they are combined with characters with code points 0x100 or larger, in
242 which case all characters need to become UTF-8 encoded), but if the
243 "encoding" pragma is present, even the 0x80..0xFF range always gets
244 UTF-8 encoded.
245
246 After all, the best thing about this pragma is that you don't have to
247 resort to \x{....} just to spell your name in a native encoding. So
248 feel free to put your strings in your encoding in quotes and regexes.
249
250 tr/// with ranges
251
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 char‐
339 acters 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 The Logic of :locale
363
364 The logic of ":locale" is as follows:
365
366 1. If the platform supports the langinfo(CODESET) interface, the code‐
367 set returned is used as the default encoding for the open pragma.
368
369 2. If 1. didn't work but we are under the locale pragma, the environ‐
370 ment variables LC_ALL and LANG (in that order) are matched for
371 encodings (the part after ".", if any), and if any found, that is
372 used as the default encoding for the open pragma.
373
374 3. If 1. and 2. didn't work, the environment variables LC_ALL and LANG
375 (in that order) are matched for anything looking like UTF-8, and if
376 any found, ":utf8" is used as the default encoding for the open
377 pragma.
378
379 If your locale environment variables (LC_ALL, LC_CTYPE, LANG) contain
380 the strings 'UTF-8' or 'UTF8' (case-insensitive matching), the default
381 encoding of your STDIN, STDOUT, and STDERR, and of any subsequent file
382 open, is UTF-8.
383
385 This pragma first appeared in Perl 5.8.0. For features that require
386 5.8.1 and better, see above.
387
388 The ":locale" subpragma was implemented in 2.01, or Perl 5.8.6.
389
391 perlunicode, Encode, open, Filter::Util::Call,
392
393 Ch. 15 of "Programming Perl (3rd Edition)" by Larry Wall, Tom Chris‐
394 tiansen, Jon Orwant; O'Reilly & Associates; ISBN 0-596-00027-8
395
396
397
398perl v5.8.8 2001-09-21 encoding(3pm)