1encoding(3pm)          Perl Programmers Reference Guide          encoding(3pm)
2
3
4

NAME

6       encoding - allows you to write your script in non-ascii or non-utf8
7

SYNOPSIS

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

ABSTRACT

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

FEATURES THAT REQUIRE 5.8.1

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

USAGE

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 => I<ENCNAME>" form.  In this case, you cannot omit the
147           first ENCNAME.  "STDIN => undef" turns the IO transcoding
148           completely off.
149
150           When ${^UNICODE} exists and non-zero, these options will completely
151           ignored.  ${^UNICODE} is a variable introduced in perl 5.8.1.  See
152           perlrun see "${^UNICODE}" in perlvar and "-C" in perlrun for
153           details (perl 5.8.1 and later).
154
155       use encoding ENCNAME Filter=>1;
156           This turns the encoding pragma into a source filter.  While the
157           default approach just decodes interpolated literals (in qq() and
158           qr()), this will apply a source filter to the entire source code.
159           See "The Filter Option" below for details.
160
161       no encoding;
162           Unsets the script encoding. The layers of STDIN, STDOUT are reset
163           to ":raw" (the default unprocessed raw stream of bytes).
164

The Filter Option

166       The magic of "use encoding" is not applied to the names of identifiers.
167       In order to make "${"\x{4eba}"}++" ($human++, where human is a single
168       Han ideograph) work, you still need to write your script in UTF-8 -- or
169       use a source filter.  That's what 'Filter=>1' does.
170
171       What does this mean?  Your source code behaves as if it is written in
172       UTF-8 with 'use utf8' in effect.  So even if your editor only supports
173       Shift_JIS, for example, you can still try examples in Chapter 15 of
174       "Programming Perl, 3rd Ed.".  For instance, you can use UTF-8
175       identifiers.
176
177       This option is significantly slower and (as of this writing) non-ASCII
178       identifiers are not very stable WITHOUT this option and with the source
179       code written in UTF-8.
180
181   Filter-related changes at Encode version 1.87
182       ·   The Filter option now sets STDIN and STDOUT like non-filter
183           options.  And "STDIN=>I<ENCODING>" and "STDOUT=>I<ENCODING>" work
184           like non-filter version.
185
186       ·   "use utf8" is implicitly declared so you no longer have to "use
187           utf8" to "${"\x{4eba}"}++".
188

CAVEATS

190   NOT SCOPED
191       The pragma is a per script, not a per block lexical.  Only the last
192       "use encoding" or "no encoding" matters, and it affects the whole
193       script.  However, the <no encoding> pragma is supported and use
194       encoding can appear as many times as you want in a given script.  The
195       multiple use of this pragma is discouraged.
196
197       By the same reason, the use this pragma inside modules is also
198       discouraged (though not as strongly discouraged as the case above.  See
199       below).
200
201       If you still have to write a module with this pragma, be very careful
202       of the load order.  See the codes below;
203
204         # called module
205         package Module_IN_BAR;
206         use encoding "bar";
207         # stuff in "bar" encoding here
208         1;
209
210         # caller script
211         use encoding "foo"
212         use Module_IN_BAR;
213         # surprise! use encoding "bar" is in effect.
214
215       The best way to avoid this oddity is to use this pragma RIGHT AFTER
216       other modules are loaded.  i.e.
217
218         use Module_IN_BAR;
219         use encoding "foo";
220
221   DO NOT MIX MULTIPLE ENCODINGS
222       Notice that only literals (string or regular expression) having only
223       legacy code points are affected: if you mix data like this
224
225           \xDF\x{100}
226
227       the data is assumed to be in (Latin 1 and) Unicode, not in your native
228       encoding.  In other words, this will match in "greek":
229
230           "\xDF" =~ /\x{3af}/
231
232       but this will not
233
234           "\xDF\x{100}" =~ /\x{3af}\x{100}/
235
236       since the "\xDF" (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on the
237       left will not be upgraded to "\x{3af}" (Unicode GREEK SMALL LETTER IOTA
238       WITH TONOS) because of the "\x{100}" on the left.  You should not be
239       mixing your legacy data and Unicode in the same string.
240
241       This pragma also affects encoding of the 0x80..0xFF code point range:
242       normally characters in that range are left as eight-bit bytes (unless
243       they are combined with characters with code points 0x100 or larger, in
244       which case all characters need to become UTF-8 encoded), but if the
245       "encoding" pragma is present, even the 0x80..0xFF range always gets
246       UTF-8 encoded.
247
248       After all, the best thing about this pragma is that you don't have to
249       resort to \x{....} just to spell your name in a native encoding.  So
250       feel free to put your strings in your encoding in quotes and regexes.
251
252   tr/// with ranges
253       The encoding pragma works by decoding string literals in
254       "q//,qq//,qr//,qw///, qx//" and so forth.  In perl 5.8.0, this does not
255       apply to "tr///".  Therefore,
256
257         use encoding 'euc-jp';
258         #....
259         $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
260         #           -------- -------- -------- --------
261
262       Does not work as
263
264         $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;
265
266       Legend of characters above
267             utf8     euc-jp   charnames::viacode()
268             -----------------------------------------
269             \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
270             \x{3093} \xA4\xF3 HIRAGANA LETTER N
271             \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
272             \x{30f3} \xA5\xF3 KATAKANA LETTER N
273
274       This counterintuitive behavior has been fixed in perl 5.8.1.
275
276       workaround to tr///;
277
278       In perl 5.8.0, you can work around as follows;
279
280         use encoding 'euc-jp';
281         #  ....
282         eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };
283
284       Note the "tr//" expression is surrounded by "qq{}".  The idea behind is
285       the same as classic idiom that makes "tr///" 'interpolate'.
286
287          tr/$from/$to/;            # wrong!
288          eval qq{ tr/$from/$to/ }; # workaround.
289
290       Nevertheless, in case of encoding pragma even "q//" is affected so
291       "tr///" not being decoded was obviously against the will of Perl5
292       Porters so it has been fixed in Perl 5.8.1 or later.
293

EXAMPLE - Greekperl

295           use encoding "iso 8859-7";
296
297           # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.
298
299           $a = "\xDF";
300           $b = "\x{100}";
301
302           printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
303
304           $c = $a . $b;
305
306           # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
307
308           # chr() is affected, and ...
309
310           print "mega\n"  if ord(chr(0xdf)) == 0x3af;
311
312           # ... ord() is affected by the encoding pragma ...
313
314           print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
315
316           # ... as are eq and cmp ...
317
318           print "peta\n" if "\x{3af}" eq  pack("C", 0xdf);
319           print "exa\n"  if "\x{3af}" cmp pack("C", 0xdf) == 0;
320
321           # ... but pack/unpack C are not affected, in case you still
322           # want to go back to your native encoding
323
324           print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
325

KNOWN PROBLEMS

327       literals in regex that are longer than 127 bytes
328           For native multibyte encodings (either fixed or variable length),
329           the current implementation of the regular expressions may introduce
330           recoding errors for regular expression literals longer than 127
331           bytes.
332
333       EBCDIC
334           The encoding pragma is not supported on EBCDIC platforms.  (Porters
335           who are willing and able to remove this limitation are welcome.)
336
337       format
338           This pragma doesn't work well with format because PerlIO does not
339           get along very well with it.  When format contains non-ascii
340           characters it prints funny or gets "wide character warnings".  To
341           understand it, try the code below.
342
343             # Save this one in utf8
344             # replace *non-ascii* with a non-ascii string
345             my $camel;
346             format STDOUT =
347             *non-ascii*@>>>>>>>
348             $camel
349             .
350             $camel = "*non-ascii*";
351             binmode(STDOUT=>':encoding(utf8)'); # bang!
352             write;              # funny
353             print $camel, "\n"; # fine
354
355           Without binmode this happens to work but without binmode, print()
356           fails instead of write().
357
358           At any rate, the very use of format is questionable when it comes
359           to unicode characters since you have to consider such things as
360           character width (i.e. double-width for ideographs) and directions
361           (i.e. BIDI for Arabic and Hebrew).
362
363       Thread safety
364           "use encoding ..." is not thread-safe (i.e., do not use in threaded
365           applications).
366
367   The Logic of :locale
368       The logic of ":locale" is as follows:
369
370       1.  If the platform supports the langinfo(CODESET) interface, the
371           codeset returned is used as the default encoding for the open
372           pragma.
373
374       2.  If 1. didn't work but we are under the locale pragma, the
375           environment variables LC_ALL and LANG (in that order) are matched
376           for encodings (the part after ".", if any), and if any found, that
377           is used as the default encoding for the open pragma.
378
379       3.  If 1. and 2. didn't work, the environment variables LC_ALL and LANG
380           (in that order) are matched for anything looking like UTF-8, and if
381           any found, ":utf8" is used as the default encoding for the open
382           pragma.
383
384       If your locale environment variables (LC_ALL, LC_CTYPE, LANG) contain
385       the strings 'UTF-8' or 'UTF8' (case-insensitive matching), the default
386       encoding of your STDIN, STDOUT, and STDERR, and of any subsequent file
387       open, is UTF-8.
388

HISTORY

390       This pragma first appeared in Perl 5.8.0.  For features that require
391       5.8.1 and better, see above.
392
393       The ":locale" subpragma was implemented in 2.01, or Perl 5.8.6.
394

SEE ALSO

396       perlunicode, Encode, open, Filter::Util::Call,
397
398       Ch. 15 of "Programming Perl (3rd Edition)" by Larry Wall, Tom
399       Christiansen, Jon Orwant; O'Reilly & Associates; ISBN 0-596-00027-8
400
401
402
403perl v5.10.1                      2009-04-14                     encoding(3pm)
Impressum